Reputation: 7470
I'm using the HttpWebRequest
class asynchronously as seen below (its a Windows application)
private void StartWebRequest(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.BeginGetResponse(new AsyncCallback(FinishWebRequest), request);
}
private void FinishWebRequest(IAsyncResult result)
{
HttpWebResponse response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
Stream responseStream = response.GetResponseStream();
int num = 100000;
byte[] buffer = new byte[num];
int offset = 0;
while ((num2 = responseStream.Read(buffer, offset, 1000)) != 0)
{
offset += num2;
}
MemoryStream stream = new MemoryStream(buffer, 0, offset);
Bitmap bitmap = (Bitmap)Image.FromStream(stream);
bitmap.Save(@"z:\new.jpg");
response.Close();
responseStream.Close();
stream.Close();
}
But I want to give some parameters to the AsyncCallback
delegate from StartWebRequest
method, is it possible? Because I want to take picture name as parameter like :
bitmap.Save(@"z:\MYPARAMATERVALUE.jpg");
Upvotes: 2
Views: 3010
Reputation: 1502806
The simplest approach here is to use an anonymous function (an anonymous method or lambda expression), like this:
private void StartWebRequest(string url, string filename)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.BeginGetResponse(result => {
FinishWebRequest(result, request, filename);
}, null); // Don't need the state here any more
}
private void FinishWebRequest(IAsyncResult result,
HttpWebRequest request,
string filename)
{
using (HttpWebResponse response =
(HttpWebResponse) request.EndGetResponse(result))
{
// Use filename here
}
}
You can do all of this manually, of course, but you'd need to create a new class to capture the filename, create an instance of that class, and then use a method in that class for the callback delegate. That's exactly what the compiler does for you with the anonymous function.
Upvotes: 6