简体   繁体   中英

async await exception catching - which thread am I on?

I'd like to do something like this:

public async Task<int> DoWork(int parameter) {
    try {
        await OperationThatMayCompleteSynchronously(parameter);
    } catch(Exception) e { 
        if(completedSynchronously)
           doSyncThing();
        else
           doAsyncThing();
    }
}

Note: I'm running tasks on the thread pool, so there is no async context.

I'd like to be able to tell the difference between an exception thrown immediately, and I'm still on the calling thread (eg parameter is invalid causing the function to abort), and an exception thrown when the async task completes, and I'm on some other random callback thread (eg network failure)

I can work out how I might achieve this if I didn't use await , and just used ContinueWith on the async operation, but is it possible using await ?

Store the task in a variable:

var task = OperationThatMayCompleteSynchronously(parameter); //may throw

Then await it:

await task; //may throw

That way you can differentiate between the two origins for a potential exception.

Note, that async methods never throw directly. They pass exceptions through the task they return. This is true even for "validation" throws that execute before the first await.

Instead of awaiting, you can call Wait() or Result , since you claim that there's no synchronization context, and, if the exception caught is AggregateException , it was not thrown in the calling thread.

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