Notify when thread is complete, without locking calling thread

后端 未结 7 1314
既然无缘
既然无缘 2020-12-15 09:13

I am working on a legacy application that is built on top of NET 3.5. This is a constraint that I can\'t change. I need to execute a second thread to run a long running tas

7条回答
  •  别那么骄傲
    2020-12-15 09:19

    Maybe using conditional variables and mutex, or some functions like wait(), signal(), maybe timed wait() to not block main thread infinitely.

    In C# this will be:

       void Notify()
    {
        lock (syncPrimitive)
        {
            Monitor.Pulse(syncPrimitive);
        }
    }
    
    void RunLoop()
    {
    
        for (;;)
        {
            // do work here...
    
            lock (syncPrimitive)
            {
                Monitor.Wait(syncPrimitive);
            }
        }
    }
    

    more on that here: Condition Variables C#/.NET

    It is the concept of Monitor object in C#, you also have version that enables to set timeout

    public static bool Wait(
       object obj,
       TimeSpan timeout
    )
    

    more on that here: https://msdn.microsoft.com/en-us/library/system.threading.monitor_methods(v=vs.110).aspx

提交回复
热议问题