在窗体表单应用程序

时间:2016-09-20 15:08:24

标签: c#

我有以下方法,我想同时调用此方法多个。并且想要检查任何结果字符串是否包含“开始”文本然后向前移动控件,否则在任何结果字符串中等待“开始”。

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;
}

请提出实现此目的的方法。

1 个答案:

答案 0 :(得分:2)

您可以做的是编辑您的任务,使其在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...