3

I need to hit an URL but don't want to wait for response.. Just request an URL(cron) for updating data. I use this below code it wait till response comes. Please clarify.

string url = "http://exampleurl";
WebRequest request = HttpWebRequest.Create(url);
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseText = reader.ReadToEnd();
Gnanaskandhan
  • 77
  • 1
  • 7
  • 3
    If you don't need a response why do you read it? (lines 3-5) – Leonid Malyshev Jun 23 '17 at 08:07
  • 2
    You can remove the last 2 lines, once you call `GetResponse()` the request to the URL is made and your cron will be triggered. – Keyur PATEL Jun 23 '17 at 08:11
  • I tried with removing StreamReader reader = new StreamReader(response.GetResponseStream()); string responseText = reader.ReadToEnd(); these two lines but it also wait till response comes. – Gnanaskandhan Jun 23 '17 at 08:14
  • You can try to put it in a thread so you don't need to wait [This can help you. ](https://www.dotnetperls.com/thread) – Kevin Jun 23 '17 at 08:40

1 Answers1

1

Assuming you don't need the response:

This line wont let the program run the next line until the method has finished:

WebResponse response = request.GetResponse();

Therefore you could run that line as a seperate task to avoid the blocking of your code. Your code will continu to run even if the task ( getResponse() ) is not finished yet.

string url = "http://exampleurl";
WebRequest request = HttpWebRequest.Create(url);
var t = Task.Run(() => request.GetResponse() );

Documentation for Task.Run() for a better understanding.

Edit: if your running an old version of .net/c# task.run won't work, you can use Task.Factory.StartNew instead.

Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169