async methods: are there any concurrency issues the programmer must address
https://softwareengineering.stackexchange.com/questions/326327
-
23-12-2020 - |
Question
Let's say this getPhotoAsync
method can be invoked a few times a second, and that the responses from the remote server can take anywhere from half a second to thirty seconds, depending on the size of the payload. So there will be several concurrent requests pending. Does .NET keep track "behind the scenes" of which response goes with which request? Is there any chance that info
could be associated with the wrong response from the remote server?
public async Task<PhotoWithInfo> getPhotoAsync(object info, string photoid)
{
//<snip> build url with photoid
var request = WebRequest.Create(new System.Uri(url));
var response = await request.GetResponseAsync();
byte[] photo=null;
// <snip> read the response stream and return a byte array
photo = myMemoryStream.ToArray();
var foo = new PhotoWithInfo();
foo.bytes = photo;
foo.Info = info;
return foo;
}
Solution
Is there any chance that info could be associated with the wrong response from the remote server?
No.
When your await
method is executed, the framework signs your Task onto the current thread as a continuation, and returns control of execution flow back to you. So now you're holding a reference to that task. When the async method returns, the framework will populate your Task with the correct value, or it will block when you interrogate the Task for its value if the async method hasn't returned yet.
Either way, you're holding the correct Task, so you'll get the correct value back. WebRequest
is an atomic class; it doesn't share state with other instances of WebRequest
, and your usage of WebRequest
here is local to the class and the Task. Further, your WebResponse
is tied to this specific WebRequest
instance. So no, there is no possibility of race conditions, because there is no shared state.