小编Max*_*m T的帖子

使用 Task.Yield 在实现生产者/消费者模式时克服 ThreadPool 饥饿

回答问题:Task.Yield - 实际用途? 我建议使用 Task.Yield 允许池线程被其他任务重用。在这样的模式中:

  CancellationTokenSource cts;
  void Start()
  {
        cts = new CancellationTokenSource();

        // run async operation
        var task = Task.Run(() => SomeWork(cts.Token), cts.Token);
        // wait for completion
        // after the completion handle the result/ cancellation/ errors
    }

    async Task<int> SomeWork(CancellationToken cancellationToken)
    {
        int result = 0;

        bool loopAgain = true;
        while (loopAgain)
        {
            // do something ... means a substantial work or a micro batch here - not processing a single byte

            loopAgain = /* check …
Run Code Online (Sandbox Code Playgroud)

c# multithreading threadpool task-parallel-library async-await

5
推荐指数
1
解决办法
1633
查看次数