3

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);
}
  • 2
    You need to investigate `await` and `async` for C#. – garfbradaz Aug 04 '17 at 13:57
  • 1
    You're running the download on the UI thread so it can't respond while the download is taking place. You need to learn about threading. – Equalsk Aug 04 '17 at 14:00
  • @garfbradaz try to searching about this, thanks – AliMajidiFard9 Aug 04 '17 at 14:04
  • @Equalsk so you are sure it isn't possible ? – AliMajidiFard9 Aug 04 '17 at 14:05
  • 1
    The first answer is given you a clue (2.). BUT when you start adding `async` methods to your application, you will find the design will start changing (if you do it properly). Good luck mate. – garfbradaz Aug 04 '17 at 14:08
  • 2
    It's absolutely possible but you need to understand _why_ this isn't working first, and it's not working because you're using the UI thread. When you understand threading you'll know the answer and next time can do it properly. Mindlessly copying and pasting someone else's code to solve a problem does not make you a good developer... – Equalsk Aug 04 '17 at 14:09
  • 1
    Excellent advice garfbradaz. Learning async should turn your entire programming paradigm inside out :) – hoodaticus Aug 04 '17 at 14:10
  • 1
    Thanks @hoodaticus! :) Love your answer too :P – garfbradaz Aug 04 '17 at 14:13
  • @garfbradaz thanks man, still testing – AliMajidiFard9 Aug 04 '17 at 14:14
  • 1
    @Equalsk sure, I try to be like what you expect, thanks for your suggest , will fight :) – AliMajidiFard9 Aug 04 '17 at 14:15
  • The basic rule btw is that you never run anything that takes any significant - and especially an unpredictable or unbounded - amount of time on the UI thread unless of course it's a pure UI task. Performing any kind of I/O other than to the video card on the UI thread is a no no. – hoodaticus Aug 04 '17 at 14:18

1 Answers1

1

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

hoodaticus
  • 3,772
  • 1
  • 18
  • 28