【发布时间】:2018-02-16 23:07:27
【问题描述】:
为了在多线程环境中测试供应商的 DLL,我想确保可以并行调用特定的方法。
目前我只是生成了几个线程并执行了一些操作,但我无法控制同时发生哪些操作。
我有点不知道应该使用什么,在锁和监视器、等待句柄、互斥锁等之间。
这只是一个测试应用程序,所以不需要“最佳实践”,我只想确保线程 1 上的旋转(快速操作)与线程 2 上的加载(慢速操作)同时运行。
这基本上是我需要的:
var thread1 = new Thread(() => {
// load the data ; should take a few seconds
Vendor.Load("myfile.json");
// wait for the thread 2 to start loading its data
WaitForThread2ToStartLoading();
// while thread 2 is loading its data, rotate it
for (var i = 0; i < 100; i++) {
Vendor.Rotate();
}
});
var thread2 = new Thread(() => {
// wait for thread 1 to finish loading its data
WaitForThread1ToFinishLoading();
// load the data ; should take a few seconds
Vendor.Load("myfile.json");
// this might run after thread 1 is complete
for (var i = 0; i < 100; i++) {
Vendor.Rotate();
}
});
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
我用锁和布尔值做了一些事情,但它不起作用。
【问题讨论】:
-
见stackoverflow.com/questions/2538065/… - 你应该看看使用 WaitHandles 来同步不同线程中代码的运行
-
VS 有很好的工具来解决冻结和在调试时使用线程; msdn.microsoft.com/en-us/library/ms164746.aspx
-
只需使用 2 个
ManualResetEvents。当 XXX 发生时,使用event.WaitOne()代替WaitForXXX和event.Set()。
标签: c# .net multithreading