我正在尝试使用webform上的按钮来处理添加用户邮件黑猩猩。我有两个函数...一个调用async函数调用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。这只会使每次通话看起来都成功,即使不是。我在这里缺少什么?
答案 0 :(得分:4)
根据您的说明,您尝试根据SubscribeEmailAsync
调用的结果从mailChimpManager.Members.GetAllAsync(listId)
方法返回响应。
由于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;
}
希望这有帮助。