在窗口窗体应用程序中多次调用异步方法
本文关键字:调用 异步方法 窗口 窗体 应用程序 | 更新日期: 2023-09-27 18:07:59
我有以下方法,我想在同一时间多次调用这个方法。并且想要检查任何结果字符串是否包含"Start"文本,然后将控件向前移动,否则等待任何结果字符串中出现"Start"。
public async Task<string> ProcessURLAsync(string url, ExtendedWebClient oExtendedWebClient, string sParam)
{
ExtendedWebClient oClient = new ExtendedWebClient(false);
oClient.CookieContainer = oExtendedWebClient.CookieContainer;
oClient.LastPage = "https://www.example.co.in/test/getajax.jsf";
byte[] PostData = System.Text.Encoding.ASCII.GetBytes(sParam);
Headers.Add("User-Agent", "Mozilla/5.0 (Windows T 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36");
Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
Headers.Add("Content-Type", "application/x-www-form-urlencoded");
oClient.Headers.Remove("X-Requested-With");
oClient.Headers.Add("X-Requested-With", "XMLHttpRequest");
var byteArray = await oClient.UploadDataTaskAsync(url, PostData);
string result = System.Text.Encoding.UTF8.GetString(byteArray);
return result;
}
请建议如何做到这一点
你可以做的是编辑你的任务,使它在while循环中运行,只有在找到你的值时才退出。
然后,使用循环创建一个任务列表,迭代尽可能多的任务,你希望它同时运行。
那么你可以使用Task.WhenAny
public async Task<string> ProcessURLAsync(string url, ExtendedWebClient oExtendedWebClient, string sParam)
{
string result = "";
while (!result.Contains("Start"))
{
ExtendedWebClient oClient = new ExtendedWebClient(false);
oClient.CookieContainer = oExtendedWebClient.CookieContainer;
oClient.LastPage = "https://www.example.co.in/test/getajax.jsf";
byte[] PostData = System.Text.Encoding.ASCII.GetBytes(sParam);
Headers.Add("User-Agent", "Mozilla/5.0 (Windows T 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36");
Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
Headers.Add("Content-Type", "application/x-www-form-urlencoded");
oClient.Headers.Remove("X-Requested-With");
oClient.Headers.Add("X-Requested-With", "XMLHttpRequest");
var byteArray = await oClient.UploadDataTaskAsync(url, PostData);
result = System.Text.Encoding.UTF8.GetString(byteArray);
}
return result;
}
然后像这样使用:
List<Task> taskList = new List<Task>();
for(int i = 0; i < 20; i++) //Run 20 at a time.
taskList.Add(ProcessURLAsync(url, webClient, "whatever"));
await Task.WhenAny(taskList);
//Value found! Continue...