Reputation:
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:
ConfigureAwait(false)
allows that the portion of the code that starts with the line this.count += read;
can be executed on any threadpool thread, correct?MyReadAsync
, there is no guarantee that the portion of the code that starts with this.count += read;
will be executed on the same thread, correct?this.count += read;
should be protected with appropriate thread synchronization primitives, correct?Upvotes: 6
Views: 1096
Reputation: 30097
Yes, you are correct. To avoid any thread synchronization issues you should apply appropriate locking around the line that is incrementing the count
Upvotes: 3