试图导致死锁c#

时间:2015-12-29 01:07:18

标签: c# multithreading

我试图模拟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);
            }
        }

    }

使用:

public class WatchesCollection
{
    public List<string> Names = new List<string>();
}

我的第二个帖子&#34; MainTask&#34;方法是:

   public void MainTask(WatchesCollection collection)
    {
        lock (collection)
        {
            collection.Names.Add("Current");
            while(_stopRequired == true) { }
        }
    }

我认为如果该方法锁定&#34;集合&#34;实例永远,&#34;锁定&#34;在主线程方法中会触发异常 - 但它不会

0 个答案:

没有答案