.NET 4.x WebClient.DownloadDataAsync блокирует вызывающий поток - C#
Формулировка задачи:
есть код
на этой строке client.DownloadDataAsync(new Uri("http://infinum.orgfree.com/_Update/APKToolGUI/version.txt")); программа подвисает на несколько секунд (2-4), хотя по идее не должна. я бы не назвал это блокировкой вызывающего потока, но как это назвать правильно хз. что с моим кодом не так?
private void CheckForUpdate()
{
using (WebClient client = new WebClient())
{
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
try
{
client.DownloadDataAsync(new Uri("http://infinum.orgfree.com/_Update/APKToolGUI/version.txt"));
}
catch (Exception e)
{
MessageBox.Show(e.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}Решение задачи: «.NET 4.x WebClient.DownloadDataAsync блокирует вызывающий поток»
textual
Листинг программы
private BackgroundWorker getVersion;
private void InitializeGetVersion()
{
getVersion = new BackgroundWorker();
getVersion.DoWork += new DoWorkEventHandler(getVersion_DoWork);
getVersion.RunWorkerCompleted += new RunWorkerCompletedEventHandler(getVersion_RunWorkerCompleted);
}
private void getVersion_DoWork(object sender, DoWorkEventArgs e)
{
using (WebClient webClient = new WebClient())
{
try
{
String actualVersionString = webClient.DownloadString("http://infinum.orgfree.com/_Update/APKToolGUI/version.txt");
Version latestVersion;
if (Version.TryParse(actualVersionString, out latestVersion))
{
e.Result = latestVersion;
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, Application.ProductName);
}
}
}
private void getVersion_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Result != null)
{
Version latestVersion = (Version)e.Result;
MessageBox.Show("Latest version: " + latestVersion.ToString(), Application.ProductName);
}
}
private void button1_Click(object sender, EventArgs e)
{
//DownloadFile();
if (!getVersion.IsBusy)
getVersion.RunWorkerAsync();
}