试图造成死锁c#
我试图在C#中模拟死锁。我写了一个简单的程序,但无法获得异常。主要方法如下:试图造成死锁c#,c#,multithreading,C#,Multithreading,我试图在C#中模拟死锁。我写了一个简单的程序,但无法获得异常。主要方法如下: static void Main(string[] args) { WatchesCollection collection = new WatchesCollection(); Actor actor = new Actor(); Thread actorThread = new Thread(() => actor.MainTask(collec
static void Main(string[] args)
{
WatchesCollection collection = new WatchesCollection();
Actor actor = new Actor();
Thread actorThread = new Thread(() => actor.MainTask(collection));
actorThread.Start();
while(loop == true)
{
string s = Console.ReadLine();
lock(collection)
{
collection.Names.Add(s);
}
}
}
与:
我假设如果该方法永远锁定“collection”实例,则主线程方法中的“lock”将触发异常-但它不会首先触发异常,
loop
设置为true
?其次,当\u stopRequired
为true时,您的main任务
循环,因此变量的名称与其用法相反,没有意义。死锁不会触发异常。他们只是使你的程序死锁,停止任何进一步的进程。异常。。。什么例外?你应该试试这个。或者嵌套锁,比如。你不应该检查布尔值是否相等-只需使用while(loop)
。
public class WatchesCollection
{
public List<string> Names = new List<string>();
}
public void MainTask(WatchesCollection collection)
{
lock (collection)
{
collection.Names.Add("Current");
while(_stopRequired == true) { }
}
}