I’m developing a WPF XBAP application that provides API to user through JavaScript by using BrowserInteropHelper. After rewriting managed part in new async-await fashion there is a need to wait until async operation is finished without making calling method async Task itself. I have :
public string SyncMethod(object parameter)
{
var sender = CurrentPage as MainView; // interop
var result = string.Empty;
if (sender != null)
sender.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(async () =>
{
try
{
result = await sender.AsyncMethod(parameter.ToString());
}
catch (Exception exception)
{
result = exception.Message;
}
}));
return result;
}
This method returns string.Empty because that happens right after execution. I’ve tried to assign this action to DispatcherOperation and do while(dispatcherOperation.Status != Completed) { Wait(); }, but even after execution the value is still empty. dispatcherOperation.Task.Wait() or dispatcherOperation.Task.ContinueWith() also didn’t help.
edit
Also tried
var op = sender.Dispatcher.BeginInvoke(...);
op.Completed += (s, e) => { var t = result; };
But t is empty too because assignment happens before awaiting of asynchronous method.
edit
Long story short, SyncMethod JavaScript interop handler helper wrapper, and all operations it runs must be on Dispatcher. AsyncMethod is async Task< T > and works perfectly when executed and awaited from inside application, i.e. inside some button handler. It has a lot of UI-dependent logic (showing status progressbar, changing cursor, etc.).
edit
AsyncMethod :
public async Task<string> AsyncMethod(string input)
{
UIHelpers.SetBusyState(); // overriding mouse cursor via Application.Current.Dispatcher
ProgressText = string.Empty; // viewmodel property reflected in ui
var tasksInputData = ParseInput(input);
var tasksList = new List<Task>();
foreach (var taskInputDataObject in tasksInputData)
{
var currentTask = Task.Factory.StartNew(() =>
{
using (var a = new AutoBusyHandler("Running operation" + taskInputData.OperationName))
{ // setting busy property true/false via Application.Current.Dispatcher
var databaseOperationResult = DAL.SomeLongRunningMethod(taskInputDataObject);
ProgressText += databaseOperationResult;
}
});
tasksList.Add(insertCurrentRecordTask);
}
var allTasksFinished = Task.Factory.ContinueWhenAll(tasksList.ToArray(), (list) =>
{
return ProgressText;
});
return await allTasksFinished;
}
This is one of the most difficult things you can try to do.
And this situation makes it near-impossible.
The problem is that you need to block
SyncMethodwhich is running on the UI thread, while allowingAsyncMethodto dispatch to the UI message queue.There are a couple of approaches you could take:
TaskusingWaitorResult. You can avoid the deadlock problem described on my blog by usingConfigureAwait(false)inAsyncMethod. This meansAsyncMethodwill have to be refactored to replace UI-dependent logic withIProgress<T>or other nonblocking callbacks.Personally, I think (1) is cleaner.