从 Task.Run C# 中的 try/catch 返回异常

Returning exception from try/catch within Task.Run C#

我正在尝试使用网络表单上的按钮来处理将用户添加到邮件黑猩猩的过程。我有两个函数...一个按钮函数调用调用 API.

的异步函数
public class MailChimpResponse
{
    public bool IsSuccessful;
    public string ReponseMessage;
}

public void SubscribeEmail(object Sender, EventArgs e)
{
    var mcResponse = SubscribeEmailAsync();
    var result = mcResponse.Result;

    if (result.IsSuccessful == true)
    {
        lblSuccess.Text = result.ReponseMessage;
        pnlSuccess.Visible = true;
    }
    else
    {
        lblError.Text = result.ReponseMessage;
        pnlError.Visible = false;
    }
}

public async Task<MailChimpResponse> SubscribeEmailAsync()
{
    IMailChimpManager mailChimpManager = new MailChimpManager(ConfigurationManager.AppSettings["testing"]);
    MailChimpResponse mcResponse = new MailChimpResponse();
    var listId = "xxxxxxxxx";

    return await Task.Run(() =>
    {
        try
        {
            var mailChimpListCollection = mailChimpManager.Members.GetAllAsync(listId).ConfigureAwait(false);

            mcResponse.IsSuccessful = true;
            mcResponse.ReponseMessage = "Success!";
        }
        catch (AggregateException ae)
        {
            mcResponse.IsSuccessful = false;
            mcResponse.ReponseMessage = ae.Message.ToString();
        }

        return mcResponse;
    });

当前填充 "var mailChimpListCollection" 的行应该失败并抛出异常(我可以通过 Intellisense 看到它)但是它继续使用 TRY 而不是落入 CATCH。这只会让每个调用看起来都成功,即使实际上并没有。我在这里错过了什么?

根据您的描述,您正试图根据 mailChimpManager.Members.GetAllAsync(listId) 调用的结果 return 来自 SubscribeEmailAsync 方法的响应。 由于 GetAllAsync 方法是一个异步方法,而不是 returning 成员列表,它 return 是一个跟踪结果检索工作的任务。你真的错过了等待,你根本不需要人为的 Task.Run 。这里我将如何重写 SubscribeEmailAsync 方法:

public async Task<MailChimpResponse> SubscribeEmailAsync()
{
    IMailChimpManager mailChimpManager = new MailChimpManager(ConfigurationManager.AppSettings["testing"]);
    MailChimpResponse mcResponse = new MailChimpResponse();
    var listId = "xxxxxxxxx";

    try
    {
        var mailChimpListCollection = await mailChimpManager.Members.GetAllAsync(listId).ConfigureAwait(false);

        mcResponse.IsSuccessful = true;
        mcResponse.ReponseMessage = "Success!";
    }
    catch (AggregateException ae)
    {
        mcResponse.IsSuccessful = false;
        mcResponse.ReponseMessage = ae.Message.ToString();
    }

    return mcResponse;
}

希望对您有所帮助。