同步.net中的特定线程操作

时间:2018-02-16 14:49:45

标签: c# .net multithreading

为了在多线程环境中测试供应商的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();

我用锁和布尔做了一些事情,但它没有用。

1 个答案:

答案 0 :(得分:4)

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