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

问题描述 投票:0回答:1

试图这样做,但得到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);
        }
    });
}

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

c# multithreading synchronization
1个回答
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);
}
© www.soinside.com 2019 - 2024. All rights reserved.