c# - SynchronizationAttribute.SUPPORTED 创建同步内容

标签 c# multithreading synchronization

根据 article下面的类不是线程安全的:

根据我的理解,我的代码有不同的同步内容:

[Synchronization]
public class Deadlock : ContextBoundObject
{
  public DeadLock Other;
  public void Demo() { Thread.Sleep (1000); Other.Hello(); }
  void Hello()       { Console.WriteLine ("hello");        }
}

public class Test
{
  static void Main()
  {
    Deadlock dead1 = new Deadlock();
    Deadlock dead2 = new Deadlock();
    dead1.Other = dead2;
    dead2.Other = dead1;
    new Thread (dead1.Demo).Start();
    dead2.Demo();
  }
}

确实如此,而且很好。但我决定通过设置来使用同步属性:

[Synchronization(SynchronizationAttribute.SUPPORTED)]

SUPPORTED 表示:

Joins the existing synchronization context if instantiated from another synchronized object, otherwise remains unsynchronized

由于控制台应用程序没有同步内容,我希望两个对象都没有同步对象,并且不应陷入死锁。但我仍然有僵局。为什么?

进一步删除了 [Synchronization] 属性。仍然有僵局。对象的[Synchronization]属性有什么影响?

最佳答案

在这里您在线程之间创建循环依赖,这可能会导致您出现 stackoverflow 异常,因为您没有在此处捕获异常,您可能无法查看它。我建议您使用 UnObservedExcpetion 处理程序,它会给您 excpetion 或尝试通过放置 try, catch block 来处理同一函数中的 excpetion。

为避免这种情况,您最好使用 AutoResetEvent .下面是相同的示例代码。

public class MyThreadTest
{
    static readonly AutoResetEvent thread1Step = new AutoResetEvent(false);
    static readonly AutoResetEvent thread2Step = new AutoResetEvent(true);

    void DisplayThread1()
    {
        while (true)
        {
            thread2Step.WaitOne(); 
            Console.WriteLine("Display Thread 1");
            Thread.Sleep(1000);
            thread1Step.Set();
        }
    }

    void DisplayThread2()
    {
        while (true)
        {
            thread1Step.WaitOne(); 
            Console.WriteLine("Display Thread 2");
            Thread.Sleep(1000);
            thread2Step.Set();
        }
    }

    void CreateThreads()
    {
        // construct two threads for our demonstration;
        Thread thread1 = new Thread(new ThreadStart(DisplayThread1));
        Thread thread2 = new Thread(new ThreadStart(DisplayThread2));

        // start them
        thread1.Start();
        thread2.Start();
    }

    public static void Main()
    {
        MyThreadTest StartMultiThreads = new MyThreadTest();
        StartMultiThreads.CreateThreads();
    }
}

关于c# - SynchronizationAttribute.SUPPORTED 创建同步内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47528625/

相关文章:

c# - System.Windows.Forms.Application 和 System.Windows.Application 之间的互操作性

c# - 调试 Windows 服务 - 防止无法启动服务

r - 在R中如何控制BLAS并行矩阵乘积中的多线程

ruby - Ruby 的 Net::HTTP 在 JRuby 上是线程安全的吗

java - 线程实例新旧java

c# - 无法远程返回自定义 HTTP 错误详细信息

c++ - AfxBeginThread 破坏了作为参数传递给线程函数的类中的 LPWSTR 值。为什么?

c - 多线程 C/C++ 变量无缓存 (Linux)

java - Conway 生命游戏的多线程 Java 程序 - 边界单元的竞争

c# - 将 byte[] 转换为 float[] 的最快方法是什么,反之亦然?