Consider the following code:
using System.IO;
using System.Threading.Tasks;
public class MyClass
{
private int count;
public async Task<int> MyReadAsync(Stream stream, byte[] buffer)
{
var read = await
stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
this.count += read;
return read;
}
}
Let’s assume that this MyReadAsync method is directly called from an event handler of a WPF application, as follows:
private async void OnWhatever(object sender, EventArgs args)
{
await myObject.MyReadAsync(this.stream, this.buffer);
}
Here are my questions:
- Using
ConfigureAwait(false)allows that the portion of the code that starts with the linethis.count += read;can be executed on any threadpool thread, correct? - For two separate calls of
MyReadAsync, there is no guarantee that the portion of the code that starts withthis.count += read;will be executed on the same thread, correct? - If 1 & 2 are correct, then it seems to me that the code
this.count += read;should be protected with appropriate thread synchronization primitives, correct?
Yes, you are correct. To avoid any thread synchronization issues you should apply appropriate locking around the line that is incrementing the count