如何在每次返回ThreadPool.QueueUserWorkItem方法时调用完成方法
本文关键字:方法 调用 QueueUserWorkItem ThreadPool 返回 | 更新日期: 2023-09-27 18:29:30
我正在使用
System.Threading.ThreadPool.QueueUserWorkItem(x => MyMethod(param1, param2, param3, param4, param5));
每次对MyMethod的调用完成时,我都想从主线程调用以下方法:
UpdateGui()
{
}
我该怎么做?
谢谢!
保持工作项的全局计数器排队并保护它的对象:
int runningTasks = 0;
object locker = new object();
每次添加任务时,递增计数器:
lock(locker) runningTasks++;
System.Threading.ThreadPool.QueueUserWorkItem(x => MyMethod(param1, param2, param3, param4, param5));
在MyMethod
结束时,递减计数器并向主线程发送信号:
lock(locker)
{
runningTasks--;
Monitor.Pulse(locker);
}
在主线程中(假设这不是GUI线程!):
lock(locker)
{
while(runningTasks > 0)
{
Monitor.Wait(locker);
UpdateGUI();
}
}
这样,您也有一个障碍来等待所有未决任务完成。
如果您不想等待,只需完全跳过主线程,并在MyMethod
完成时调用UpdateGUI
将更新转发到GUI线程即可。
注意在MyMethod
中,您应该有某种形式的Dispatcher.BeginInvoke
(WPF)或Control.BeginInvoke
(WinForms),否则您无法安全地更新GUI!
在线程池方法的末尾将对updategui方法的调用发布回ui线程的同步上下文。。。
示例:
private SynchronizationContext _syncContext = null;
public Form1()
{
InitializeComponent();
//get hold of the sync context
_syncContext = SynchronizationContext.Current;
}
private void Form1_Load(object sender, EventArgs e)
{
//queue a call to MyMethod on a threadpool thread
ThreadPool.QueueUserWorkItem(x => MyMethod());
}
private void MyMethod()
{
//do work...
//before exiting, call UpdateGui on the gui thread
_syncContext.Post(
new SendOrPostCallback(
delegate(object state)
{
UpdateGui();
}), null);
}
private void UpdateGui()
{
MessageBox.Show("hello from the GUI thread");
}
假设MyMethod
是一个同步方法,在QueueUserWorkItem
内部调用以使其异步执行,则可以使用以下方法:
ThreadPool.QueueUserWorkItem(x =>
{
MyMethod(param1, param2, param3, param4, param5);
UpdateGui();
});
注意必须通过调用Invoke
/BeginInvoke
来更新UpdateGui()
中的GUI元素。
这可以让客户端更干净,让类处理跨线程切换机制。通过这种方式,GUI以正常的方式使用您的类。
public partial class Form1 : Form
{
private ExampleController.MyController controller;
public Form1()
{
InitializeComponent();
controller = new ExampleController.MyController((ISynchronizeInvoke) this);
controller.Finished += controller_Finished;
}
void controller_Finished(string returnValue)
{
label1.Text = returnValue;
}
private void button1_Click(object sender, EventArgs e)
{
controller.SubmitTask("Do It");
}
}
GUI表单订阅类的事件,而不知道它们是覆盖线程。
public class MyController
{
private ISynchronizeInvoke _syn;
public MyController(ISynchronizeInvoke syn) { _syn = syn; }
public event FinishedTasksHandler Finished;
public void SubmitTask(string someValue)
{
System.Threading.ThreadPool.QueueUserWorkItem(state => submitTask(someValue));
}
private void submitTask(string someValue)
{
someValue = someValue + " " + DateTime.Now.ToString();
System.Threading.Thread.Sleep(5000);
//Finished(someValue); This causes cross threading error if called like this.
if (Finished != null)
{
if (_syn.InvokeRequired)
{
_syn.Invoke(Finished, new object[] { someValue });
}
else
{
Finished(someValue);
}
}
}
}