根据 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/