在创建对象的线程上调用方法 [英] Invoking method on thread which created object

查看:116
本文介绍了在创建对象的线程上调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在线程T上创建了一个对象O。如何从线程T的内部对象O中获取,并调用该线程上的方法?这样,创建对象的表单就不需要这样:

  private void ChangeProgress(int value )
{
progressBar1.Value = value;
}

void FD_ProgressChanged(object sender,DownloadEventArgs e)
{
if(InvokeRequired)
{
Invoke(new Action< int> ;(ChangeProgress),new object [] {e.PercentDone});
}
else ChangeProgress(e.PercentDone);
}

这只是丑陋,要求谁使用对象来弄清楚哪些事件在创建对象的同一个线程上生成,而不是添加 if(InvokeRequired)... else 代码,而不是添加每个单个事件处理程序的代码。我认为如果对象本身负责在正确的线程上调用事件,那将会更加优雅。这是可能的吗?

解决方案

使用BackgroundWorker类。它照顾所有这一切。注意ReportProgress事件。


Let's say I created an object O on the thread T. How can I get, from inside object O the thread T and invoke a method on that thread?. This way, it won't be necessary for the form that created the object to to this:

    private void ChangeProgress(int value)
    {
        progressBar1.Value = value;
    }

    void FD_ProgressChanged(object sender, DownloadEventArgs e)
    {
        if (InvokeRequired)
        {
            Invoke(new Action<int>(ChangeProgress), new object[] { e.PercentDone });
        }
        else ChangeProgress(e.PercentDone);
    }

which is just ugly and requires whoever uses the object to either figure out which events are raised on the same thread that created the object and which are not and add the if(InvokeRequired)...else code on the ones that are not, or just add the code on every single event handler. I think it would be more elegant if the object itself takes care of invoking the event on the right thread. Is this possible?

解决方案

Use the BackgroundWorker class. It takes care of all this. Note the ReportProgress event.

这篇关于在创建对象的线程上调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆