await / async中的闭包和线程安全

时间:2018-03-28 09:38:20

标签: c# async-await task-parallel-library

我对参数和闭包捕获中的线程安全有一些想法。我将尝试使用示例进行说明。

示例1

请考虑以下代码,取自Taurus: A New Star in the Test Automation Tools Constellation

private async void DownloadFileButton_Click(object sender, EventArgs e)
{
   // Since we asynchronously wait, the UI thread is not blocked by the file   download.
  await DownloadFileAsync(fileNameTextBox.Text);

  // Since we resume on the UI context, we can directly access UI elements.
  resultTextBox.Text = "File downloaded!";
}

我关心的是UI线程访问fileNameTextBox.Text,而DownloadFileAsync(...)可能会在线程池线程上运行。

这段代码是否是线程安全的?是因为字符串是不可变的吗?如果DownloadFileAsync()的参数是一个数组会怎么样?

示例2

同样的问题,但有闭包。例如,以下代码线程是否安全?

private async void SomeAsyncCalculation(object sender, EventArgs e)
{
    await Task.Factory.StartNew(() => {
        SomeCalculation(uiOwnedArray);
    }
}

我不是,因为uiOwnedArray是在没有同步的情况下从多个线程访问的。我该如何缓解这种情况?

0 个答案:

没有答案