I need to asynchronously get data from the same page and do not block main thread.
I tried to use DownloadDataAsync method of class WebClient but it seems that it behave not truly in async manner.
For testing this I make code
private void button1_Click(object sender, EventArgs e)
{
checkLink_async();
Thread.CurrentThread.Join(5000);
checkLink_async();
Thread.CurrentThread.Join(5000);
checkLink_async();
Thread.CurrentThread.Join(5000);
}
/// <summary>
/// Check the availability of IP server by starting async read from input sensors.
/// </summary>
/// <returns>Nothing</returns>
public void checkLink_async()
{
string siteipURL = "http://localhost/ip9212/getio.php";
Uri uri_siteipURL = new Uri(siteipURL);
// Send http query
WebClient client = new WebClient();
try
{
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(checkLink_DownloadCompleted_test);
client.DownloadDataAsync(uri_siteipURL);
tl.LogMessage("CheckLink_async", "http request was sent");
}
catch (WebException e)
{
tl.LogMessage("CheckLink_async", "error:" + e.Message);
}
}
private void checkLink_DownloadCompleted_test(Object sender, DownloadDataCompletedEventArgs e)
{
tl.LogMessage("checkLink_DownloadCompleted", "http request was processed");
}
The result from log:
01:32:12.089 CheckLink_async http request was sent
01:32:17.087 CheckLink_async http request was sent
01:32:22.097 CheckLink_async http request was sent
01:32:27.102 checkLink_DownloadComplet http request was processed
01:32:27.102 checkLink_DownloadComplet http request was processed
01:32:27.102 checkLink_DownloadComplet http request was processed
I expected that each started DownloadDataAsync method will run in parallel and completes during main thread code runnig (I emulate this in a code by using Thread.CurrentThread.Join). But it seems that neither of DownloadDataAsync calls were finished before button1_Click ended (despite there was plenty of time).
Is there any way to change this behavior or I should use another approach?