【问题标题】:Does a long running loop with async IO needs the LongRunning option?带有异步 IO 的长时间运行循环是否需要 LongRunning 选项?
【发布时间】:2016-05-20 01:13:23
【问题描述】:

我读过一个长时间运行的任务被认为是阻塞线程的任务,因此需要用LongRunning 选项标记它,以便任务调度程序更愿意为该任务分配一个新线程。

具有异步 IO 的任务也被视为长时间运行?

例子:

//This method can run for hours
async Task ListenerLoop(CancellationToken Cancel, NetworkStream stream)
{
      while(!Cancel.IsCancellationRequested)
      {
                var CancelTimeoutOrReadSource = new CancellationTokenSource();
                var TimeoutTask = Task.Delay(TimeSpan.FromSeconds(ReadTimeout), CancelTimeoutOrReadSource.Token);
                var ReadTask = stream.ReadAsync(b, 0, b.Length, CancelTimeoutOrReadSource.Token);

                if (await Task.WhenAny(TimeoutTask, ReadTask) == TimeoutTask)
                {
                    CancelTimeoutOrReadSource.Cancel(); 
                    return;
                }
                else
                {
                    CancelTimeoutOrReadSource.Cancel(); 
                    //readed bytes count
                    c = ReadTask.Result;
                }

                //read 'c' bytes from array 'b'

                //Give time to other tasks to run (Is this correct?)
                await Task.Delay(5000);
      }
}

【问题讨论】:

    标签: c# asynchronous task-parallel-library


    【解决方案1】:

    简短的回答,不。对于背景阅读,请尝试http://blog.stephencleary.com/2013/11/there-is-no-thread.html

    此外,您不需要最后的 await Task.Delay 来为异步等待场景中的其他工作留出时间。

    关于长期运行选项,请参阅https://social.msdn.microsoft.com/Forums/en-US/8304b44f-0480-488c-93a4-ec419327183b/when-should-a-taks-be-considered-longrunning?forum=parallelextensions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多