0

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.

1

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer.My call to SendEmailAlert is actually a "fire and forget" type .So I wont be using TAP design pattern.Please suggest any other approach.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.