Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
试图造成死锁c#_C#_Multithreading - Fatal编程技术网

试图造成死锁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

我试图在C#中模拟死锁。我写了一个简单的程序,但无法获得异常。主要方法如下:

    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) { }
        }
    }