Vasilii Ruzov
Vasilii Ruzov

Reputation: 554

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

Upvotes: 0

Views: 1452

Answers (1)

krillgar
krillgar

Reputation: 12805

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();

Upvotes: 5

Related Questions