Multiple asynchronous HttpRequests in C# - c#

I have to send two HTTP requests: The second one should be sent while I'm waiting for response from the first one. The responses should be received independently, so it can happen that either response can arrive first. How do I do this in C#? Should I use 2 HttpClients or not and how?

Yes I have resolved it. I'm making 2 HttpRequestMessage, then twice httpClient.SendAsync(request)
so it is
var a=httpClient.SendAsync(request1);
var b=httpClient.SendAsync(request2);
and then I'm getting both responses like
a.GetAwaiter().GetResult();
b.GetAwaiter().GetResult();

Related

Reroute incoming request

How can I send a received request to another url, and send the response to the original sender?
I have an ashx generic handler and can get the sent request using Request.InputStream . However - that doesn't include everything (like headers). Is there a way of sending the whole request as is, and then sending the whole response as is?
Just to be completely clear: a.ashx gets an HttpContext from somewhere.com. I want it to send the response as if somewhere.com was communicating directly with b.ashx.
Have you considered using the Server.Transfer to redirect the query to the required url?
Simply use
Server.Transfer("Page2.aspx", true);

Parallel HTTPRequest using HttpClient in Windows 8 app

I am using HttpClient for sending HTTP requests and receiving HTTP responses in my Windows 8 app. I have few questions on the same:
1) Can I send multiple/parallel HTTP requests using a single HttpClient object? Is there a recommended way to use HttpClient object efficiently?
2) What is the difference when I create HttpClient object every time and when I re-use the same object for each new request?
3) I am tracking the requests and responses using Fiddler. What I found out is that the response time in Fiddler is different than the response time I am calculating manually inside my App. The response time for a request in Fiddler is always lower than the calculated response time in my app. Can anybody please tell me why it is like that?
4) One more thing I came across is that for every request it is doing HTTPS handshake. Instead it should do it only first time. I checked it using Fiddler and it is clearly visible there. Is there any property I need to set in HttpClient object to stop this from doing it every time.
5) Whether HttpClient is thread-safe?
1 & 5:
HttpClient manual:
The following methods are thread safe:
CancelPendingRequests
DeleteAsync
GetAsync
GetByteArrayAsync
GetStreamAsync
GetStringAsync
PostAsync
PutAsync
SendAsync
2 & 4:
HttpClient manual:
The HttpClient class instance acts as a session to send HTTP requests.
3:
Fiddler acts as a proxy. Your browser sends the request to Fiddler, which forwards it to the origin server. This adds upon the request time.
Make sure that you use the same HttpClient object for each async HttpRequest which will prevent it from overlapping the requests

Is it wise to use SMTP.SendAsync in asp.net

I'm writing a code that sends 2 codes to 2 different emails (to check that owner of both emails are the same person). And I got the error:
System.InvalidOperationException: An asynchronous call is already in progress. It must be completed or canceled before you can call this method. Well I can simply avoid this error sending the second email after the sending of the first one completes, but the question is that if so many users at the same time request email sending (forgotten password, email change, registration, ...) would it cause problem? or I will get this error only when they are executed repeatedly at the same page?
Thanks in advance,
Ashkan
The purpose of the SendAsync method is not to block the calling thread; however, you must wait for the SendAsync method to finish before you can send a new email on the same SmtpClient instance. In other words, create 2 instances, one for each email, and send them both asynchronously if you want.
From MSDN:
After calling SendAsync, you must wait for the e-mail transmission to
complete before attempting to send another e-mail message using Send
or SendAsync.
As Icarus pointed out, you have to wait for the SendAsync to finish before calling it on the same instance. In addition to that, it is possible to have ThreadPool starvation, but your mileage will vary based on your implementation. Internally, SendMailAsync uses a ThreadPool thread to perform the task. I wouldn't be concerned if it's just an email here and there though.
No Separate instances won't be a problem. if many users send requests at the same time they each will be different instances.

C# HTTPWebRequest Cannot Be Used to Access a URL Periodically?

I am writing a program to crawl Web pages using C# HTTTWebRequest. Since I need to monitor the updates of a specific URL, I write the code as follows. However, I noticed that I could get responses for two times only. After that, it got no responses. Even though I lengthen the period to one minute, I still got the same problem. I don't understand why. Could you give me a hand? Thanks so much!
GreatFree
while (true)
{
WebRequest http = HttpWebRequest.Create("http://www.sina.com.cn");
HttpWebResponse response = (HttpWebResponse)http.GetResponse();
Console.WriteLine(response.LastModified);
Thread.Sleep(5000);
}
imaximchuk's answer is correct, but it doesn't explain why.
HTTP connections are pooled - one connection will be reused for a new request if it's available - and returning the connection to the pool occurs when you close or dispose the web response. In your case, you're not closing or disposing the response, so it's not being returned to the pool. There's a maximum number of connections to any particular host, which is configurable but usually shouldn't be changed. The default is two connections - which is why you're seeing two working responses and then a timeout.
I believe there's a finalizer somewhere which will release the connection when it notices the relevant object is eligible for garbage collection, but that's non-deterministic.
Basically: always close a web response, ideal using a using statement.
while (true)
{
WebRequest http = WebRequest.Create("http://www.sina.com.cn");
using (HttpWebResponse response = (HttpWebResponse)http.GetResponse())
{
Console.WriteLine(response.LastModified);
}
Thread.Sleep(5000);
}
You should call response.Close() when you have finishied working with respose or use using(HttpWebResponse response ... to close it automatically

Web Services. Get input data, process it at background thread

I've got several web-services: asmx,wcf. At couple of them there are some methods, which take a lot of time for processing, but size of input data for these methods are small and it takes not much time to transfer on the wire. I want move to not sync model. Client passes data to service, service answers that data transfer was correct and process it at background thread witout connection with client. So agter transfering connection should be closed. IS it possible? Can u help me with articles or may be just google request.
John is right - Once you close an http connection, it is done. You can't get back to the same process.
So if you can use another technology that allows duplex on one connection (e.g. WCF), do it!
However,
if you have no choice but to use webservices,
here are three ways to make it work. You may get timeouts on any of them.
Option 1:
Forget the part about 'client answers data was correct.' Just have each thread make its request and wait for the data.
Option 2:
Now, assuming that won't work and you must do the validation, this way requires the client to make 2 requests.
First request: returns valid/invalid.
Second request: returns the long-running results.
Variation of option 2:
If you have timeout problems, you could have the first request generate a GUID or unique database key and start another process, passing it this key, and return the key to the client. (if you can get the server to allow you to start a process - depends on security settings/needs - if not you may be able to start an async thread and have it keep running after the websvc one ends?) The process will do the long task, update the row in the database w/ the unique id when finished, revealing the results plus a 'done' flag. The second request by the client could always return immediately and if the processing is not done, return that, if it is, return the results. The client will repeat this every 5 sec or so until done.
Hacks, I know, but we don't always have a choice for the technology we use.
Don't do this with ASMX web services. They weren't designed for that. If you must do it with ASMX, then have the ASMX pass the data off to a Windows Service that will do the actual work, in the background.
This is more practical with WCF.
We have been writing stuff to interact with the UK gov website and the way they handle something similar is that you send your request and data to the server and it responds saying, roughly, "thanks very much - we're processing it now, please call back later using this id" - all in an XML message. You then, at some point later, send a new http request to the service saying, essentially, "I'm enquiring about the status of this particular request id" and the server returns a result that says either it has processed OK, or processed with errors, or is still processing, please try again in xx seconds.
Similar to option 2 described previously.
It's a polling solution rather than a callback or 2 way conversation but it seems to work.
The server will need to keep, or have access to, some form of persistent table or log for each request state - it can contain eg, the id, the original request, current stage through the workflow, any error messages so far, the result (if any) etc. And the web service should probably have passed the bulk of the request off to a separate Windows service as already mentioned.

Categories