在创建对象的线程上调用方法 [英] Invoking method on thread which created object
问题描述
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屋!