Karan Karan - 2 months ago 7
C# Question

Call async method multiple time in window form application

I have following method , i want to call this method multiple at same time. and want to check if any of the result string contains "Start" text then move control forward otherwise wait for "Start" in any result string.

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


please suggest way to achieve this.

Answer

What you could do, is edit your Task so that it runs in a while loop and only exits when your value is found.

Then, create a list of tasks using a loop, iterating through as many tasks as you want it to run simultaneously .

Then you can use 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;
}

And then use it like this:

        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...