Advertisement
ivandrofly

TaskScheduler.Current Explained

Aug 8th, 2023 (edited)
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. The TaskScheduler.Current property in C# is from the .NET framework and represents the TaskScheduler that is currently executing or the default TaskScheduler if there is no current scheduler.
  2. In other words, TaskScheduler.Current represents the TaskScheduler responsible for executing the currently running Task.
  3. This can be the default task scheduler provided by the .Net framework (which uses ThreadPool to queue and execute tasks), or a custom task scheduler.
  4. For instance, a custom TaskScheduler could be created for UI-related Tasks in a Windows Forms or WPF application, that ensure that the Tasks are executed on the UI thread.
  5. Here's a simple example (considering a Console application within a Task):
  6.  
  7. Task.Factory.StartNew(() => {
  8. Console.WriteLine(TaskScheduler.Current == TaskScheduler.Default);
  9. }).Wait();
  10.  
  11. If you run this code, it will print True, because in a Console application, the current task scheduler and the default one are the same.
  12. However, if you run this in a UI context of a WPF or Windows Forms application, it would be False because the scheduler, that is responsible for executing this currently running task, is the UI thread's scheduler (synchronisation context takes care of creating this), not the default one provided by .NET.
  13.  
  14.  
  15.  
  16. # Note: I think the AI made a slight mistake, the explaining would make sense if the code above was in .ContinueWith and
  17. when the user specified the TaskScheduler.FromCurrentSynchronizationContext()
  18. With Task.Run or Task.Factory.StartNew() you are never guaranteed that the execution will be on the main thread even if you are
  19. in UI e.g: Winform or wpf!
  20.  
  21.  
  22. # Sources Rider AI (Subtitle Edit history)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement