I currently have the following:
var tasks = new List<Task>();
foreach (myObject obj in myObjectList)
{
tasks.Add(downloadBitmap(obj.profilePath, obj.id));
}
await Task.WhenAll(tasks);
downloadBitmap
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
RequestState myRequestState = new RequestState();
myRequestState.request = request;
// Start the asynchronous request.
IAsyncResult result = request.BeginGetResponse(new AsyncCallback(RespCallback), Tuple.Create(myRequestState, actorID));
// this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), request, DefaultTimeout, true);
// The response came in the allowed time. The work processing will happen in the
// callback function.
allDone.WaitOne();
RespCallBack
Tuple<RequestState, int> state = (Tuple<RequestState, int>)asynchronousResult.AsyncState;
RequestState myRequestState = state.Item1;
int actorID = state.Item2;
try
{
HttpWebRequest myHttpWebRequest = myRequestState.request;
myRequestState.response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(asynchronousResult);
// Read the response into a Stream object.
Stream responseStream = myRequestState.response.GetResponseStream();
myRequestState.streamResponse = responseStream;
Bitmap bitmap = new Bitmap(responseStream);
// Do some work here
}
catch (WebException e)
{
Console.WriteLine("\nRespCallback Exception raised!");
Console.WriteLine("\nMessage:{0}", e.Message);
Console.WriteLine("\nStatus:{0}", e.Status);
}
finally
{
// Release the HttpWebResponse resource.
myRequestState.response.Close();
}
allDone.Set();
I got most of this from the MSDN
website. I am also receiving the warning:
This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
for the DownloadBitmap
function.
I understand that I am not using await
in this function but the reason I thought it wasn't necessary anywhere was because BeginGetResponse
is already asynchronous
?
Not sure if my understanding of this is entirely correct...