Task.Yield - real usages?

前端 未结 6 2053
-上瘾入骨i
-上瘾入骨i 2020-12-01 05:29

I\'ve been reading about Task.Yield , And as a Javascript developer I can tell that\'s it\'s job is exactly the same as setTime

6条回答
  •  情深已故
    2020-12-01 05:58

    I think that nobody provided the real answer when to use the Task.Yield. It is mostly needed if a task uses a never ending loop (or lengthy synchronous job), and can potentially hold a threadpool thread exclusively (not allowing other tasks to use this thread). This can happen if inside the loop the code runs synchronously. the Task.Yield reschedules the task to the threadpool queue and the other tasks which waited for the thread can be executed.

    The example:

      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 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 for loop end && */  cancellationToken.IsCancellationRequested;
                if (loopAgain) {
                    // reschedule  the task to the threadpool and free this thread for other waiting tasks
                    await Task.Yield();
                }
            }
            cancellationToken.ThrowIfCancellationRequested();
            return result;
        }
    
        void Cancel()
        {
            // request cancelation
            cts.Cancel();
        }
    

提交回复
热议问题