【问题标题】:Synchronize specific threads actions in .net在 .net 中同步特定线程操作
【发布时间】: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();

我用锁和布尔值做了一些事情,但它不起作用。

【问题讨论】:

标签: c# .net multithreading


【解决方案1】:

这只是一个示例,如何使用等待句柄来同步线程……我用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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多