为了在多线程环境中测试供应商的 DLL,我想确保可以并行调用特定方法。
现在我只是生成几个线程并执行一些操作,但我无法控制同时发生哪些操作。
我有点不知道我应该使用什么,在锁和监视器、waithandles、mutex 等之间。
它仅用于测试应用程序,因此无需成为“最佳实践”,我只想确保线程 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();
我已经用锁和 bool 值做了一些事情,但它不起作用。
最佳答案
这只是一个示例,说明如何使用等待句柄来同步线程...我使用 Thread.Sleep()
ManualResetEvent thread1WaitHandle = new ManualResetEvent(false);
ManualResetEvent thread2WaitHandle = new ManualResetEvent(false);
var thread1 = new Thread(() => {
Console.WriteLine("Thread1 started");
// load the data ; should take a few seconds
Thread.Sleep(1000);
// wait for the thread 2 to start loading its data
thread1WaitHandle.Set();
Console.WriteLine("Thread1 wait");
thread2WaitHandle.WaitOne(-1);
Console.WriteLine("Thread1 continue");
// while thread 2 is loading its data, rotate it
for (var i = 0; i < 100; i++)
{
Thread.Sleep(10);
}
});
var thread2 = new Thread(() => {
Console.WriteLine("Thread2 started");
// wait for thread 1 to finish loading its data
Console.WriteLine("Thread2 wait");
thread1WaitHandle.WaitOne(-1);
Console.WriteLine("Thread2 continue");
// load the data ; should take a few seconds
Thread.Sleep(1000);
thread2WaitHandle.Set();
// this might run after thread 1 is complete
for (var i = 0; i < 100; i++)
{
Thread.Sleep(10);
}
});
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
关于c# - 在 .net 中同步特定线程操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48829236/