c# - 如何保证我的 Async 方法线程安全?

标签 c# multithreading asynchronous win-universal-app iot

我需要在我的 Windows 通用应用程序中编写一个方法来写入 SD 卡。在下面的方法中,如何确保两个线程不会同时尝试写入同一个文件?

public async void WriteToCard(string strFileName, IEnumerable<string> listLinesToWrite)
{
    IStorageItem item = await folder.GetItemAsync(strFileName);
    StorageFile file = (StorageFile)item;

    await Windows.Storage.FileIO.WriteLinesAsync(file, listLinesToWrite);
}

最佳答案

您可以保留一个带有 ConcurrentDictionary 的映射,它将每个文件映射到一个 SemaphoreSlim。然后,根据您要写入的文件位置获取每个信号量:

private ConcurrentDictionary<string, SemaphoreSlim> fileLocks = new ConcurrentDictionary<string, SemaphoreSlim>();

public async Task WriteToCardAsync(string strFileName, IEnumerable<string> listLinesToWrite)
{
   var semaphoreSlim = fileLocks.GetOrAdd(strFileName, new SemaphoreSlim(1, 1));

   await semaphoreSlim.WaitAsync();
   try
   {
       IStorageItem item = await folder.GetItemAsync(strFileName);
       StorageFile file = (StorageFile)item;

       await Windows.Storage.FileIO.WriteLinesAsync(file, listLinesToWrite);
   }
   finally
   {
       semaphoreSlim.Release();
   }
}

旁注 - 使用 async Task 而不是 async void。我还在方法中添加了 Async 后缀。

关于c# - 如何保证我的 Async 方法线程安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32102888/

相关文章:

c# - Form Flow 机器人定制问题

c# - 如何在 C# 中创建一个全局对象?

C++11 原子 : why does this code work?

objective-c - 等到 UITableView 完成 reloadData

c# - I/O 操作的 .NET 基于事件的异步模式是否会阻塞底层线程?

c# - 在 2 个 WPF 窗口之间发送事件

c# - 我如何要求用户在 C# 中输入

wpf - 如何使 WPF TreeView 数据绑定(bind)惰性和异步?

java - 如何从Java中的线程获取所有子线程?

python - gevent.http.HTTPServer API 建议流式传输,而是缓冲整个请求和响应