简体   繁体   中英

Handling exception in task

I'm new to TPL. I need to handle exception when the SendEmailAlert() method throws any error.Is the following code correct please?

public Task MyMethod()
{
    DoSomething();

    try
    {   
        string emailBody = "TestBody";
        string emailSubject = "TestSubject";

        Task.Run(()=> SendEmailAlert(arrEmailInfo));
    }
    catch (AggregateException ex)
                {
                    ex.Handle((e) =>
                       {
                           log.Error("Error occured while sending email...", e);
                           return true;
                       }
                       );
                }

}

private void SendEmailAlert(string[] arrEmailInfo)
{
    MyClassX.SendAlert(arrEmailnfo[0], arrEmailnfo[1]);
}

I forced an error from within SendEmailAlert() method.But the exception is not getting caught. Could someone advise?

Thanks.

Your Task.Run runs in a different context (you would need a try/catch inside it; or check if the task is done). You could change to use async/await.

Example:

public async void MyMethod()
{
    try
    {
        await ExceptionMethod();
    }
    catch (Exception ex)
    {
        // got it
    }
}

public async Task ExceptionMethod()
{
    throw new Exception();
}

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