I am new to async and was wondering if any improvement can be made to the solution I put together from scattered information on the web.
The following (working) code shows how a button press runs logic and if there are any errors they will appear in the returned task.Exception.Handle
variable which I can check in my ContinueWith
code. If it's not null, I open the error dialog window for the user. By passing in FromCurrentSynchronizationContext
, I get to open the window on the UI thread and avoid issues with UI thread access.
Any improvements to make it more readable or suggest a different patter for this would be much welcomed.
public void StartButton()
{
//prevent multiple button presses with IsRunning switch
if (!IsRunning)
{
IsRunning = true;
Threading.Task.Factory.StartNew(() =>
{
ProgramLogic();
IsFabRunning = false;
})
.ContinueWith(p =>
{
if (p.Exception != null)
p.Exception.Handle(x =>
{
logger.Error(p.Exception);
windowManager.ShowDialog(new ForceCloseViewModel(p.Exception.Message), null, null);
IsFabRunning = false;
return true;
});
}, Threading.TaskScheduler.FromCurrentSynchronizationContext());
}
}