In WPF one needs to use the synchronization context and the ConfigureAwait method.

An expert developer is needed to create an async framework that the average developers can use.

An example of a code sequence that needs to be used often:


public async Task<bool> LongProcessingAsync()
{
var taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
var factory = new TaskFactory(taskScheduler);
var task = factory.StartNew(() =>
{
     // Long processing code here, set a boolean succeeded/ failed status
     return status;
});

return await task;
}

// And the calling code. The way async event handlers are used in WPF
// at this moment, one cannot cancel an async event.
// This is why you have to override the OnClick method and mark it async.
// Notice how the code below cancels the event by NOT CALLING THE
// BASE CLASS OnClick METHOD!
// We've tried to handle the Preview... events async, but without success.
protected override async void OnClick()
{
    var canContinue = await LongProcessingAsync();
    if( canContinue )
    {
       base.OnClick();
     }

} 
Advertisements