ALERT!
Click here to register with a few steps and explore all our cool stuff we have to offer!
Home
Upgrade
Credits
Help
Search
Awards
Achievements
 4464

A tip when making WebRequests.

by El!teHax0rPr0 - 02-19-2016 - 07:33 AM
#1
Note: I'm only gonna be showing WebClient() examples here, considering it's higher leveled built right on top of httpwebrequest. Furthermore, it's easier.

Often times when I use programs that require WebRequests, they block the calling thread. Simple terms, the user interface freezes until it's done.


There are a few remedies to fix this but you might still run into UI freezing. 

Create a new thread:
Code:
new Thread(new ThreadStart(() => {     
    using (WebClient wc = new WebClient())
       {
          string webString = wc.DownloadString("http://www.google.com");
           Console.WriteLine(webString);
        }

})).Start();


[Image: PTfYJ3V.png?1]

Or WebClient offers a method to Download Asynchronously - https://msdn.microsoft.com/en-us/library...10%29.aspx

Code:
using (WebClient wc = new WebClient())
 {
        wc.DownloadStringCompleted += (sender, e) =>
        {
           Console.WriteLine(e.Result);
        };

wc.DownloadStringAsync(new Uri("http://google.com"));
}

[Image: 5T0Y9hk.png?1]

Now, there maybe a time where you go to put the web request in a new thread or use DownloadStringAsync() and it still blocks the UI. Why?


The simple fix is adding this line to your code:

Code:
WebRequest.DefaultProxy = null;

Why does this work?

Because before the request is even sent, It will check Internet Explorers proxy setting by default which may cause in a delay/ui freeze even though you took precautions. So setting it the null ahead of time skips that process and solves problems.
This account is currently banned
Ban reason: Learn from your mistakes.
Reply
#2
(02-19-2016 - 07:59 AM)Anonymous Wrote: Why are you using ThreadStart()? You could just be doing

Code:
new Thread(()=>{});

Also, in this instance, it'd be easier to use a Task. Using an HTTPClient is also a bit more modern, but that's just my opinion.

I'm not overly sure why I use ThreadStart, theres literally no difference. Personal preference I guess. The compiler just turns this

Code:
new Thread(() => { }).Start();

to this anyway

Code:
new Thread(new ThreadStart() => { }).Start();

I wasn't really showing the best way considering an httpclient is the best-of-both-worlds so to speak. I was just explaining why it will still freeze if you took those precautions. None the less, appreciate the feedback.
This account is currently banned
Ban reason: Learn from your mistakes.
Reply
#3
thanks for this share :)




Reply
#4
(02-19-2016 - 08:33 AM)Silentgaming Wrote: thanks for this share :)

Anytime bro!
This account is currently banned
Ban reason: Learn from your mistakes.
Reply
#5
Thanks for the share bruv
Reply

Users browsing: 2 Guest(s)