与Task.ConfigureAwait进行线程同步(false)

时间:2012-12-07 11:32:40

标签: c# .net async-await

请考虑以下代码:

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;
    }
}

假设从WPF应用程序的事件处理程序直接调用此MyReadAsync方法,如下所示:

private async void OnWhatever(object sender, EventArgs args)
{
    await myObject.MyReadAsync(this.stream, this.buffer);
}

以下是我的问题:

  1. 使用ConfigureAwait(false)允许以行this.count += read;开头的代码部分可以在任何线程池线程上执行,对吗?
  2. 对于MyReadAsync的两次单独调用,无法保证以this.count += read;开头的代码部分将在同一个线程上执行,对吗?
  3. 如果1&amp; 2是正确的,那么在我看来代码this.count += read;应该用适当的线程同步原语保护,对吗?

1 个答案:

答案 0 :(得分:4)

是的,你是对的。为了避免任何线程同步问题,您应该在递增计数的行周围应用适当的锁定