简体   繁体   中英

Wait for async task on application exit from UI thread

I'm writing an UI app. If some exception happens I need to do some work before application exit. So I subscribed to AppDomain.CurrentDomain.UnhandledException event.

AppDomain.CurrentDomain.UnhandledException += HandleException;

HandleException method performs async saving to remote(because there are no sync api).

private void HandleException(object sender, UnhandledExceptionEventArgs args)
{
    foreach (var user in UsersCollection.ToArray())
    {
        try
        {
            foreach (var session in user.Sessions.ToArray())
            {
                try
                {
                    SaveSessionAsync(session).Wait();
                }
                catch (Exception e)
                {
                    Logger.Error("Can't save session: " + session, e);
                }
            }
        }
        catch (Exception e)
        {
            Logger.Error("Can't save sessions of user " + user, e);
        }
    }
}

Before application exit I need to be sure that I saved all sessions(tried, at least). But if I put Wait() there I get a deadlock and application never stops. As far as I know, await may help me in normal situation(when I'm in UI thread but not in app termination state), but await does not awaits on application exit. So my saving tasks may be aborted. But I need them to finish.

Is there a way of waiting for guaranteed finish of SaveSessionAsync task without creating a deadlock?

BTW: SaveSessionAsync has Parse.com API inside

You only used part of the syntax you need to run it in a non- async method. Utilizing Task.Run() will run it in an asynchronous fashion without having to use await .

Try this:

Task.Run(() => SaveSessionAsync(session)).Wait();

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