Can't use current application while using WebClient

I am trying to update some data without asking users about the Windows app, but when I try to load, the app is unused and the controls are insensitive.

code:

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

res = client.DownloadString(url);
}

      

+3


source to share


2 answers


This is most likely because you are executing your code on the UI thread. When your UI thread is busy, it cannot transmit window messages such as mouse or keyboard input. Your options:

  • Run this code in a separate thread.

  • Use asynchronous methods such as WebClient.DownloadStringAsync or DownloadStringTaskAsync.



Of these, Option 2 is best practice.

See the accepted answer of this closed-ended question "no topic" for an example of using both parameters correctly (although the numbers vary from my list here) how to use async and wait for a method that brings time

+1


source


Try the following function. If you want I can explain it to you line by line

public static string GetWebData(string url)
    {
    try {
        WebRequest request = WebRequest.Create(url);
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        Stream dataStream = response.GetResponseStream();
        StreamReader readStream = new StreamReader(dataStream);
        dynamic data = readStream.ReadToEnd();
        readStream.Close();
        dataStream.Close();
        response.Close();
        return data;
    } catch (Exception ex) {
        return "";
    }
}

      



I hope this helps

-2


source







All Articles