Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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.
- In other words, TaskScheduler.Current represents the TaskScheduler responsible for executing the currently running Task.
- 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.
- 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.
- Here's a simple example (considering a Console application within a Task):
- Task.Factory.StartNew(() => {
- Console.WriteLine(TaskScheduler.Current == TaskScheduler.Default);
- }).Wait();
- 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.
- 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.
- # Note: I think the AI made a slight mistake, the explaining would make sense if the code above was in .ContinueWith and
- when the user specified the TaskScheduler.FromCurrentSynchronizationContext()
- With Task.Run or Task.Factory.StartNew() you are never guaranteed that the execution will be on the main thread even if you are
- in UI e.g: Winform or wpf!
- # Sources Rider AI (Subtitle Edit history)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement