gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:16:41 26 4
gpt4 key购买 nike

我正在尝试使用网络表单上的按钮来处理将用户添加到邮件黑猩猩的过程。我有两个函数...一个按钮函数调用调用 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) 调用的结果从 SubscribeEmailAsync 方法返回响应.由于 GetAllAsync 方法是一个异步方法,它不返回成员列表,而是返回一个跟踪结果检索工作的任务。你真的错过了等待,你根本不需要人工 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;
}

希望这对您有所帮助。

关于c# - 从 Task.Run C# 中的 try/catch 返回异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48849363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com