温馨提示:本文翻译自stackoverflow.com,查看原文请点击:c# - Threading
c# multithreading locking staleobjectstate

c# - 穿线

发布于 2020-04-08 00:01:22

我有几个调用方法的线程。看起来像这样:

public void DoWork(params int[] initialConditions)
{
    //Do a lot of work
}

但是,如果条件变化很快,我会得到很多过时的中间结果,因为我不能足够快地完成计算。我知道!我将代码修改如下:

public void DoWork(params int[] initialConditions)
{
    if(Monitor.TryEnter(syncLock)
    {
        //Do a lot of work
        Monitor.Exit(syncLock);
    }
}

现在,除非我以前的计算完成,否则我将不费吹灰之力进行计算。在瞬息万变的情况下,我会落后一点,但不会比以前多得多,而且我不会浪费时间做所有额外的工作来获得陈旧的结果。

然而,

一旦情况停止改变,我仍然有点过时,想要调用DoWork的最终线程早已消失。有没有办法告诉线程:

if no one is doing work
    do work
else
    wait to do work until after the other thread finishes
but
    if a new thread arrives before you start doing work, leave without doing work.

查看更多

提问者
bwall
被浏览
80
AlbertK 2020-02-07 00:50

此代码应满足您的伪代码描述的要求:

class Program
{
    static object _workLockObject = new object();
    static volatile int _currentPriority = 0;

    static void Main()
    {
        Task t1 = new Task(() => TryDoWork(1));
        Task t2 = new Task(() => TryDoWork(2));
        Task t3 = new Task(() => TryDoWork(3));

        t1.Start();
        Thread.Sleep(100);
        t2.Start();
        Thread.Sleep(100);
        t3.Start();
        Console.ReadKey();
    }
    public static void TryDoWork(params int[] initialConditions)
    {
        var priotity = Interlocked.Increment(ref _currentPriority);
        while (!Monitor.TryEnter(_workLockObject))// starting to wait when DoWork is available
        {
            if (priotity != _currentPriority) // if the thread has stale parameters
            {
                Console.WriteLine("DoWork skipped " + initialConditions[0]);
                return;// skipping Dowork
            }
            Thread.Sleep(300);// Change the interval according to your needs
        }
        try // beginning of critical section
        {
            if (priotity == _currentPriority) // if the thread has the newest parameters
                DoWork(initialConditions);
        }
        finally
        {
            Monitor.Exit(_workLockObject); // end of critical section
        }
    }
    public static void DoWork(params int[] initialConditions)
    {
        Console.WriteLine("DoWork started " + initialConditions[0]);
        Thread.Sleep(5000);
        Console.WriteLine("DoWork ended " + initialConditions[0]);
    }
}

Interlocked.Increment保证每个线程都有其自己的优先级,而最新线程具有一个允许在DoWork可用时执行的优先级