A pattern to pause/resume an async task?

前端 未结 5 1388
耶瑟儿~
耶瑟儿~ 2020-11-28 09:12

I have a mostly IO-bound continuous task (a background spellchecker talking to a spellcheck server). Sometimes, this task needs to be put on hold and resumed later, dependin

5条回答
  •  野性不改
    2020-11-28 09:50

    All the other answers seem either complicated or missing the mark when it comes to async/await programming by holding the thread which is CPU expensive and can lead to deadlocks. After lots of trial, error and many deadlocks, this finally worked for my high usage test.

    var isWaiting = true;
    while (isWaiting)
    {
        try
        {
            //A long delay is key here to prevent the task system from holding the thread.
            //The cancellation token allows the work to resume with a notification 
            //from the CancellationTokenSource.
            await Task.Delay(10000, cancellationToken);
        }
        catch (TaskCanceledException)
        {
            //Catch the cancellation and it turns into continuation
            isWaiting = false;
        }
    }
    

提交回复
热议问题