user49572
user49572

Reputation:

Thread synchronization with Task.ConfigureAwait(false)

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:

  1. Using 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?
  2. For two separate calls of 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?
  3. 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?

Upvotes: 6

Views: 1096

Answers (1)

Haris Hasan
Haris Hasan

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

Related Questions