![]() ![]() The DoSomethingElse method works fine when called alone, but as soon at it's invoked by the event, the UI freezes since TaskFactory.Current will reuse the synchronization context task scheduler from my library continuation.įinding out this could take some time, especially if the second task call is buried down in some complex call stack. He or she follows examples found everywhere on the web and simply use without specifying the TaskScheduler (and there is no easy overload to specify it at the second parameter). Here, the person writing the library call chose to start a new Task when the operation completes. (() => Thread.Sleep(5000)) // simulate a long operation Private void DoSomethingElse() // the event handler MyLibrary.DoSomeOperationAsync() // call that triggers the event asynchronously MyLibrary.SomeOperationCompleted += (s, e) => DoSomethingElse() Now, let's make a call to this library on a button click in a WPF or WinForms application: private void Button_OnClick(object sender, EventArgs args) }, TaskScheduler.FromCurrentSynchronizationContext()) OnSomeOperationCompleted() // trigger the event }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default) ![]() Thread.Sleep(1000) // simulate a long operation SomeOperationCompleted?.Invoke(this, EventArgs.Empty) Public event EventHandler SomeOperationCompleted I decide to use the Task Parallel Library for implementation because it's really easy to implement this behavior with the following code: public class MyLibrary Suppose I am writting a library of asynchronous methods, using the standard async pattern based on events to signal completion on the original synchronisation context, in the exact same way XxxAsync methods do in the. This is absolutely not obvious at first glance in the documentation nor samples.Ĭurrent can lead to subtle bugs since its behavior is changing depending on whether you're inside another task. However, there's something really bothering me: the fact that TaskScheduler.Current is the default task scheduler, not TaskScheduler.Default. ![]() The Task Parallel Library is great and I've used it a lot in the past months. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |