【发布时间】:2023-03-06 22:17:01
【问题描述】:
我正在学习异步等待并在我的旧 asp.net 中实现。我正在使用 c# 4.6。
现在页面在添加 async-await 后总是同步运行。它正在等待 api 发回结果,然后在屏幕上显示消息。
我正在寻找的是该页面启动一个线程并做出响应(我可以在上面做其他事情)。完成后,它会显示结果。
下面是我的按钮点击、HTTP 调用(将启动异步请求)和 API 方法。
我有
- 遵循示例https://msdn.microsoft.com/en-us/library/hh191443.aspx
- 在 StackOverflow 和其他论坛上寻找解决方案。我相信我也是这样做的(当然我不是:()。
在 aspx 页面上添加了Async="true"。
按钮点击
protected async void btnCopy_Click(object sender, EventArgs e)
{
await RunAsync(Guid.Parse(SourceBusinessID), Guid.Parse(DestinationBusinessID), false);
if (lblError.Text == "")
{
lblError.Text = "Copy Completed!";
}
}
public async Task RunAsync( Guid SourceBusinessID, Guid DestinationBusinessID,bool copyAdviser)
{
using (var client = new HttpClient())
{
var request = new HttpRequestMessage()
{
RequestUri = new Uri("http://localhost:52140/api/DummyAccounts/"),
Method = HttpMethod.Get,
};
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/plain"));
client.Timeout = TimeSpan.FromSeconds(500);
var response = await client.SendAsync(request);
if (!response.IsSuccessStatusCode)
{
lblError.Text = response.StatusCode.ToString();
}
}
}
API
public IHttpActionResult Get(Guid sourceBusinessID, Guid destinationBusinessID,bool copyAdviser = true)
{
try
{
CopyHelper.SourceBusinessID = sourceBusinessID;
CopyHelper.DestinationBusinessID = destinationBusinessID;
CopyHelper.CopyAdviser = copyAdviser;
logger.Info("Copy buisness started:" + DateTime.Now);
bool status = CopyBusinessService.CopyBusiness(CopyHelper.SourceBusinessID, CopyHelper.DestinationBusinessID, CopyHelper.CopyAdviser);
if (status)
{
logger.Info("Copy business finished:" + DateTime.Now);
return Ok(true);
}
else
{
logger.Info("Copy business failed:" + DateTime.Now);
return Ok(false);
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
任何帮助将不胜感激。
【问题讨论】:
-
我想你可能有点困惑。我建议阅读 Stephen Cleary 的 Async doesn't change the HTTP protocol。
-
感谢@Damien_The_Unbeliever 这真的很有帮助。
标签: c# asp.net multithreading asynchronous async-await