Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

c# - async/await exception handling pattern

I have the following reoccurring try/catch pattern in my code. Using a try/catch block to handle any exceptions thrown when calling a method in orionProxy.

async private void doGetContacts()
{
    try {
        currentContacts = await orionProxy.GetContacts (); // call method in orionProxy
        ShowContacts (); // do something after task is complete
    }
    catch (Exception e) {
        orionProxy.HandleException (e); // handle thrown exception
    }
}

What I would like to write is something like the following.

async private void doGetContacts()
{
    currentContacts = await orionProxy.CheckForException(orionProxy.GetContacts ());
    ShowContacts (); // do something after task is complete but shouldn't run on exception
}

Any pointers/suggestions? I've tried various forms of Actions/Tasks/Lambdas but nothing will properly trap the exception in orionProxy.CheckForException(?) so ShowContacts doesn't run.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't see why it wouldn't work, assuming GetContacts is an async method:

public async Task<T> CheckForExceptionAsync<T>(Task<T> source)
{
  try
  {
    return await source;
  }
  catch (Exception ex)
  {
    HandleException(ex);
    return default(T);
  }
}

On a side note, you should avoid async void (as I describe in my MSDN article) and end your async method names with the Async suffix.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...