C# SynchronizationAttribute.SUPPORTED创建同步内容
根据以下类别,它不是线程安全的: 我的代码被锁定,但据我所知,有不同的同步内容:C# SynchronizationAttribute.SUPPORTED创建同步内容,c#,multithreading,synchronization,C#,Multithreading,Synchronization,根据以下类别,它不是线程安全的: 我的代码被锁定,但据我所知,有不同的同步内容: [Synchronization] public class Deadlock : ContextBoundObject { public DeadLock Other; public void Demo() { Thread.Sleep (1000); Other.Hello(); } void Hello() { Console.WriteLine ("hello"); }
[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)]
支持的
表示:
如果从中实例化,则加入现有同步上下文
另一个已同步对象,否则将保持不同步
由于控制台应用程序并没有同步内容,我希望这两个对象都并没有同步对象,并且不应该陷入死锁。但我仍然有僵局。为什么?
此外,我们已经完全删除了
[Synchronization]
属性。仍然有僵局。是什么影响使对象具有属性?这里您正在创建线程之间的循环依赖,这可能会导致stackoverflow异常,因为您没有捕获exception,所以您可能无法查看它。我建议您使用unobservedexception
处理程序,该处理程序将为您提供exception,或者通过放置try,catch
块,尝试在同一函数中处理exception
为了避免这种情况,你最好利用它。下面是相同的示例代码
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();
}
}
如果您长时间运行代码,您将很快收到stackoverlfow异常…您收到了吗??…您正在创建循环依赖项我无法复制此项。无论是支持还是不支持
[同步]
我都没有死锁。因为超时时间太长,所以不会出现溢出。但我有了主意,准备接受答案。@vico注意,无论您等待多久,这里都不会出现堆栈溢出。接受一个根本不能回答你们问题的答案是很奇怪的。我不知道这个答案和这个问题有什么关系,也不知道为什么会被接受。提供的代码中不存在“线程之间的循环依赖关系”,也不可能存在堆栈溢出异常。@Evk-我不确定StackOverflowException是否存在循环依赖关系,因为这行是dead1。其他=dead2;dead2.其他=dead1;在这个存储彼此引用的两个对象中,它在线程之间创建循环依赖关系,但这是完全正常的,并且不会在提供的代码中产生任何问题,它只是用来模拟死锁条件。问题是关于[Synchronization]
属性及其工作原理,但您在回答中根本没有提到这个属性。@Evk-问题的最后一行进一步删除了[Synchronization]属性。仍然有僵局。什么影响使[同步]成为对象的属性?@Evk-如果你选择AutoEvent,我认为不需要同步