Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Asynchronous Web requests in C# WPF

In my application i have a WPF Window that has a DataGrid in it. In Window_Loaded event I get JSON data from server and after deserializing it and converting it into a List<T> i bind that to my data grid. Everything is working fine this way.

The problem:

But the request part of code takes time and the whole window seems white with no elements loaded including the data grid.I want to make the request part asynchronous just as in AJAX we show a loader image while something is loading and then using a callback function to show the content when it is loaded.

In step by step

  1. Load the window and elements data grid buttons etc..
  2. Make web request to server and show 'data is loading..' in a label possibly.
  3. Fire an event or something that notifies that data has loaded and then bind the data grid to list so that the application remains responsive and active during whole web request part.

Here is the current non-async code i am using in Window_Loaded event handler

 WebResponse response = req.GetResponse();
 Stream responseStream = response.GetResponseStream();
 StreamReader sr = new StreamReader(responseStream, Encoding.UTF8);
 string JSON = sr.ReadToEnd();
 List<MyObject> returnedData = JsonConvert.DeserializeObject<List<MyObject>>(JSON);

i found this link but i am not sure how it is applicable to my problem. Any help or idea for how to go about this is welcome.

like image 803
Yaseen Avatar asked Jan 24 '26 21:01

Yaseen


1 Answers

Any reason you're not using the WebClient Class? Have a look at the WebClient.DownloadStringAsync Method.

like image 196
dtb Avatar answered Jan 26 '26 12:01

dtb