我需要在我的 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/