![](/img/trans.png)
[英]How to wait for one task to finish before calling another without blocking?
[英]How to wait for Async Task method to finish before calling it again?
我在这样的 for 循环中调用 Async Task 方法:-
for(int event_dbID = get_maxID_old + 1 ; event_dbID <= get_maxID_new ; event_dbID++)
{
SqlCommand command3 = new SqlCommand(queryString3, connection);
command3.Parameters.Add("@ID", (int)event_dbID);
SqlDataReader reader3 = command3.ExecuteReader();
while (reader3.Read())
{
c8y_Event_MSG = Convert.ToString(reader3[0]);
c8y_pushEvent(c8y_Event_MSG); //calling async method
}
reader3.Close();
}
for
循环可以根据情况运行数百次迭代。
JSON 字符串作为参数传递给异步任务方法。 异步任务方法如下所示:-
public async Task c8y_pushEvent(string Event_MSG)
{
//Doing bunch of operations on Event_MSG
using (var client = new HttpClient())
{
//Making a get request using a value from a key in Event_MSG
//Storing response of get request
HttpResponseMessage get_response = await client.GetAsync("https://myurl.com/"+controllerName);
var get_responseString = await get_response.Content.ReadAsStringAsync();
//Doing bunch of operations on get_responseString
//Making a Post request passing this get_responseString as Content-Message in stringContent
HttpResponseMessage response = await client.PostAsync("https://myurl.com", stringContent);
var responseString = await response.Content.ReadAsStringAsync();
}
}
现在,发生的事情是所有 Post 请求都成功了,但它们的顺序不正确。
例如。 如果通过 Post 请求收到的数据序列应如下所示:1,2,3,4,5 它以随机顺序出现,如:2,3,1,5,4
将等待 Async 方法完全完成,然后在c8y_pushEvent(c8y_Event_MSG);
做一些改变? 如果是,那么如何等待它一次完成一个字符串 JSON 的执行,然后传递下一个字符串 JSON?
是否建议这样做? 它会引起任何问题吗?
您需要等待该方法:
await c8y_pushEvent(c8y_Event_MSG); //calling async method
要使用await
关键字,您需要在父方法中添加async
关键字。
但是如果你想同步运行异步方法,那就是另外一个问题了。 SO上已经有答案了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.