简体   繁体   中英

Returning value from async Action invoked on Dispatcher

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, ie 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;    
}

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.

This is one of the most difficult things you can try to do.

AsyncMethod is async Task< T > and works perfectly when executed and awaited from inside application, ie inside some button handler. It has a lot of UI-dependent logic

And this situation makes it near-impossible.


The problem is that you need to block SyncMethod which is running on the UI thread, while allowing AsyncMethod to dispatch to the UI message queue.

There are a couple of approaches you could take:

  1. Block on the Task using Wait or Result . You can avoid the deadlock problem described on my blog by using ConfigureAwait(false) in AsyncMethod . This means AsyncMethod will have to be refactored to replace UI-dependent logic with IProgress<T> or other nonblocking callbacks.
  2. Install a nested message loop. This should work but you'll have to think through all the re-entrancy ramifications.

Personally, I think (1) is cleaner.

do this:

var are = new AutoResetEvent(true);
sender.Dispatcher.Invoke(DispatcherPriority.Normal,                                      
        new Action(async () =>
        {
           try { ... } catch { ... } finally { are.Set(); }
        }));



are.WaitOne();
return result;

are.WaitOne() will tell AutoResetEvent to wait until it is signaled which will happen when dispatcher action reaches finally block where are.Set() is called.

This solved it for me.

Add Task delay for invoker to complete .

public string SyncMethod(object parameter)  
{
    var sender = CurrentPage as MainView; // interop
    var result = string.Empty;

    if (sender != null)
    {
        await sender.Dispatcher.Invoke(DispatcherPriority.Normal,
            new Func<Task>(async () =>
            {
                try
                {
                    result = await sender.AsyncMethod(parameter.ToString());
                }
                catch (Exception exception)
                {
                    result = exception.Message;
                }
            }));
    }

    await Task.Delay(200); // <-- Here
    return result;        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM