SynchronizationAttribute.SUPPORTED创建同步内容

时间:2017-11-28 09:59:11

标签: 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表示:

  

如果实例化,则加入现有的同步上下文   另一个同步对象,否则保持不同步

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

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

1 个答案:

答案 0 :(得分:1)

这里你创建了线程之间的循环依赖,这可能会导致你的stackoverflow异常,因为你没有在这里捕获excpetion你可能无法查看它。我建议您使用UnObservedExcpetion处理程序,通过放置try, catch块来激活或尝试处理同一函数中的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();
    }
}