C#异步的ThreadStart和恢复同步
问题描述:
我希望异步启动6个线程,暂停他们并同步恢复...C#异步的ThreadStart和恢复同步
它应该工作像这样的:
- 线程1开始(thr1.start( ))
- 线程1取得了一些进展(获取MAC-不会忽略从TXT文件,初始化COM对象)
- 线程1暂停(暂停,直到所有的线程也做了同样的线程1)
- 线程2开始
- 线程2取得了一些进展
- 线程2暂停
- 线程3起
- 线程3取得了一些进展
- 线程3暂停
- ...
- 毕竟6线程暂停,他们应该恢复所有..
我试着用6个简单的布尔标志并且等到它们都是true
但这相当有点脏......
有什么想法吗?
EDIT(更好的可视化):
Thr1 | Initiliazing |waiting |waiting | Resuming
Thr2 | waiting |Initiliazing |waiting | Resuming
Thr3 | waiting |waiting |Initiliazing | Resuming
...
感谢和格尔茨, 通量
答
你需要某种同步 - 为每个线程ManualResetEvent听起来可能,这取决于你的线程功能。
编辑:感谢您的更新 - 这里有一个基本的例子:
// initComplete is set by each worker thread to tell StartThreads to continue
// with the next thread
//
// allComplete is set by StartThreads to tell the workers that they have all
// initialized and that they may all resume
void StartThreads()
{
var initComplete = new AutoResetEvent(false);
var allComplete = new ManualResetEvent(false);
var t1 = new Thread(() => ThreadProc(initComplete, allComplete));
t1.Start();
initComplete.WaitOne();
var t2 = new Thread(() => ThreadProc(initComplete, allComplete));
t2.Start();
initComplete.WaitOne();
// ...
var t6 = new Thread(() => ThreadProc(initComplete, allComplete));
t6.Start();
initComplete.WaitOne();
// allow all threads to continue
allComplete.Set();
}
void ThreadProc(AutoResetEvent initComplete, WaitHandle allComplete)
{
// do init
initComplete.Set(); // signal init is complete on this thread
allComplete.WaitOne(); // wait for signal that all threads are ready
// resume all
}
注意,StartThreads
方法将发生阻塞而线程初始化 - 这可能会或可能不会是一个问题。
什么是你的问题域 - 可能有一些diffenrt方式来解决它 – swapneel
为什么不只是执行你的主线程中的所有6'进度',然后产生额外的线程? –
,因为'一些进度'需要在每个线程..有一些messageqeue问题,如果我初始化我主要的 – MariusK