c# - 在 .net 中同步特定线程操作

标签 c# .net multithreading

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

相关文章:

c# - 如何在四边形中找到一个随机点?

c# - 简单的类实例化在 C# 中会失败吗?

c# - 用于在给定索引处插入、删除和重新排列的高效 C# 数据结构

java - 如何在JAVA 8中处理对象的嵌套列表-顺序处理内部列表,而必须并行处理外部列表

java - 使用 AtomicReference 带有参数的单例

c# - 在c#中从字符串中获取变量数据

c# - 以字符串数组形式传入多个参数

c# - 哪个标识符变量更适合作为参数传递给方法?

来自 PowerBuilder(10 或 11.5)的 .NET dll

c++ - 通过函数调用 C++ 中的线程更改对象属性