6

考虑以下代码:

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

我们假设这个MyReadAsync方法是直接从 WPF 应用程序的事件处理程序中调用的,如下:

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 和 2 是正确的,那么在我看来this.count += read;应该使用适当的线程同步原语来保护代码,对吗?
4

1 回答 1

3

Yes, you are correct. To avoid any thread synchronization issues you should apply appropriate locking around the line that is incrementing the count

于 2012-12-07T11:45:11.327 回答