我的项目中有两个帖子,一个是异步,第二个帖子是正常但依赖于帖子1。
发布1回报" 成功"作为字符串。如果post2在post 1之前响应,那么会发生什么错误。所以我想做的就是等到第1回归" 成功"在他的回应中。
我不明白该怎么做。请建议。以下是我的帖子请求。
//发布1
startAsync(" https://www.example.com",webClient,sPostData);
//帖子2 :这取决于上面的帖子1.我希望在回复之前完成帖子1。
html = oClient.Post("https://example.com" + "?"+sPostParameter, "");
新编辑
private async void startAsync(string url, ExtendedWebClient oExtendedWebClient, string sParam)
{
await CreateMultipleTasksAsync(url, oExtendedWebClient, sParam);
}
private async Task CreateMultipleTasksAsync(string url, ExtendedWebClient oExtendedWebClient, string sParam)
{
try
{
Task<int> download1 = oExtendedWebClient.ProcessURLAsync(url, oExtendedWebClient, sParam);
Task<int> download2 = oExtendedWebClient.ProcessURLAsync(url, oExtendedWebClient, sPostData);
Task<int> download3 = oExtendedWebClient.ProcessURLAsync(url, oExtendedWebClient, sPostData);
Task<int> download4 = oExtendedWebClient.ProcessURLAsync(url, oExtendedWebClient, sPostData);
Task<int> download5 = oExtendedWebClient.ProcessURLAsync(url, oExtendedWebClient, sPostData);
// Await each task.
int length1 = await download1;
int length2 = await download2;
int length3 = await download3;
int length4 = await download4;
int length5 = await download5;
}
catch (Exception ex)
{
ErrorLog.createLog("ex.StackTrace = " + ex.StackTrace + " ex.tostring = " + ex.ToString());
}
}
async Task<int> ProcessURLAsync(string url, ExtendedWebClient oExtendedWebClient, string sParam)
{
byte[] PostData = System.Text.Encoding.ASCII.GetBytes(sParam);
var byteArray = await oExtendedWebClient.UploadDataTaskAsync(url, PostData);
//DisplayResults(url, byteArray);
return byteArray.Length;
}
我使用这样的startAsync方法 startAsync(&#34; https://www.example.com&#34;,webClient,sPostData);
这里我想等到这个结束执行
答案 0 :(得分:1)
答案 1 :(得分:0)
您的代码看起来像
Task<int> download1 = await oClient.ProcessURLAsync(url,
oWebClient,
sParam).ContinueWith(
downloadTask =>{
if (downloadTask.Result == "success"){
var html = oClient.Post(
"https://example.com" + "?" + sPostParameter,
"");
} else{
//wait
}
});
答案 2 :(得分:-2)
由于我同意这应该已经等待下载1你可以强制等待任务结果(因为你通过使用(编辑和更正,sry)将其声明为任务&lt; int &gt; :
替换
Task<int> download1 = oClient.ProcessURLAsync(url, oWebClient, sParam);
int length1 = await download1;
使用
int length1 = await oClient.ProcessURLAsync(url, oWebClient, sParam).Result;
或者,您可以使用以下方式强行等待:
Task.WaitAll(download1);
问候 康斯坦丁