如何通知解锁线程(Monitor.Wait(),PulseAll()模拟)

时间:2018-02-26 12:58:07

标签: c# multithreading synchronization

试图这样做,但得到SynchronizationLockException

static object blockObj = new object();
async void Method()
{
    await Task.Run(() =>
    {
        try
        {
            bool status = Monitor.TryEnter(blockObj);
            Debug.WriteLine("Block status: " + (!status).ToString());
            if (!status)
            {
                Monitor.Wait(blockObj, 7000);//got SynchronizationLockException
                Debug.WriteLine("Other did the job");
                return;
            }
            else
            {
                //Imitation of activity
                Thread.Sleep(3000);
                Monitor.PulseAll(blockObj);
                Debug.WriteLine("Completed");
            }
        }
        finally
        {
            if (Monitor.IsEntered(blockObj))
                Monitor.Exit(blockObj);
        }
    });
}

有没有办法告知代码执行的完成情况?

1 个答案:

答案 0 :(得分:0)

我没有找到使用Monitor通知解锁线程的方法。试图使用Thread.Join()走另一条路。这就是我想出的:

public static void Synchronize()
{
    if (th1 == null || !th1.ThreadState.In(System.Threading.ThreadState.Running, System.Threading.ThreadState.WaitSleepJoin))
    {
        Debug.WriteLine("Starting new thread...");
        th1 = new Thread(new ThreadStart(thr_sync));
        th1.Start();
    }
    else
        Debug.WriteLine("Thread is already started. Waiting for the end...");

    if (th1.Join(10000))
        Debug.WriteLine("Done");
    else
        Debug.WriteLine("Time out");
}
static void thr_sync()
{
    //Imitation of activity
    Thread.Sleep(3000);
}