TaskScheduler with async sequential Tasks C#

前端 未结 1 895
名媛妹妹
名媛妹妹 2021-01-22 00:09

I am executing some .py scripts async. One Script takes about 30 seconds to be executed. It could happen that two or even more Scripts are being selected in a timespan of two or

相关标签:
1条回答
  • 2021-01-22 00:34

    I solved it. There is only need of a Semaphore. It is the same way as in this Thread Here is the Code:

    private static SemaphoreSlim semaphore = new SemaphoreSlim(1);
     private Task QueueValue(int position, TaskScheduler ts)
        {
            return QueueTask(async () =>
            {
                await semaphore.WaitAsync();
                try
                {
                    var at = "This is Thread " + position + " starting";
                    updateLabel(at);
                    await Task.Delay(3000);
                    at = "Thread " + position + " is ending";
                    updateLabel(at);
                    await Task.Delay(1000);
                }
                finally
                {
    
                    semaphore.Release();
                }
    
            }, ts);
        }
    

    Many thanks!

    0 讨论(0)
提交回复
热议问题