【发布时间】:2014-11-19 23:00:22
【问题描述】:
我需要从同一个页面异步获取数据,不要阻塞主线程。
我尝试使用 WebClient 类的 DownloadDataAsync 方法,但它的行为似乎不是真正的异步方式。
为了测试这个,我编写了代码
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");
}
日志结果:
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
我希望每个启动的 DownloadDataAsync 方法都将并行运行并在主线程代码运行期间完成(我在代码中使用 Thread.CurrentThread.Join 对此进行了模拟)。 但似乎在 button1_Click 结束之前,DownloadDataAsync 调用都没有完成(尽管有足够的时间)。
有什么方法可以改变这种行为,或者我应该使用其他方法吗?
【问题讨论】:
标签: c# multithreading asynchronous webclient