Search code examples
c#webclientdownloadstring

Can't use current application during using WebClient


I have trying to update some data without asking users on windows application, but when I try to download , app isn't usable and controls aren't touchable.

Code:

using (WebClient client = new WebClient {Encoding = System.Text.Encoding.UTF8})
{
string url = "http://domain_name.com/api/getSomeData";

res = client.DownloadString(url);
}

Solution

  • This is most likely happening because you are executing your code on the UI thread. When your UI thread is busy it cannot pump window messages such as input events from the mouse or keyboard. Your options here are:

    1. Run this code on a separate thread.

    2. Use asynchronous techniques such as WebClient.DownloadStringAsync or DownloadStringTaskAsync.

    Of these, Option #2 is the better practice.

    See the accepted answer of this closed "off topic" question for an example of proper use of both options (though the numbers are swapped from my list here) how to use async and await on a method that is time comsuming