110,538
社区成员
发帖
与我相关
我的任务
分享
private static void Method() {
// Handles are used only to wait for both workers to complete
var handles = new WaitHandle[] {
new ManualResetEvent(false),
new ManualResetEvent(false),
};
// Worker's job
WaitCallback job = state => {
DoSomethings();
// Signal to the main thread that the worker has completed
((ManualResetEvent)state).Set();
};
// Run workers
ThreadPool.QueueUserWorkItem(job, handles[0]);
ThreadPool.QueueUserWorkItem(job, handles[1]);
// Wait for both workers to complete
WaitHandle.WaitAll(handles);
}
线程N:
DoSomeCaculation();
autoResetEventN.WaitOne();
DoSomethingOfUpdateUI();
volatileField=N+1;
主线程:
while(true)
{
if(volatileField==SomeValue)break;
if(volatileField==1)autoResetEvent1.Set();
if(volatileField==2)autoResetEvent2.Set();
...
}
。
(多线程我了解得也不多,上面也只是我的猜想)。 volatile bool _completedFlag
解决。在运算线程运算完后,设置完_completedFlag为true后,主线程才会被激活,否则一直等待。
void Test(string msg)
{
if (InvokeRequired)
{
this.Invoke(new Action<string>(Logging2),msg);
}
else
{
Logging2( msg);
}
}
private void Logging2(string msg)
{
//----这里写你对UI的实际操作
}
2 另一线程调用:以 ThreadPool.QueueUserWorkItem为例
ThreadPool.QueueUserWorkItem(Somemethod);
3 关键在于
if (InvokeRequired)
{
this.Invoke(new Action<string>(Logging2),msg);
}