【发布时间】:2018-02-26 17:00:19
【问题描述】:
我在 C# 中编写了一个异步方法来写入文件,但是我不断收到以下异常:
进程无法访问文件 'C:\XXX\XXX\XXX\XXX\EventBuffer.txt' 因为它正被 另一个进程。
我查看了已在 SO 上发布的类似问题,例如 this one 和 this one,但似乎我的问题的原因不同。
我使用进程监视器来查看哪些进程正在尝试访问文件所在的目录,但唯一尝试访问它的进程是我正在调试的进程(将在调试后不久发布一个 sn-p进程窗口)。
这并不是在上次访问时关闭文件之前尝试访问文件,因为当我第一次尝试访问文件时会出现异常。我试图在实例化 StreamWriter 后实现延迟,以防尝试写入方法,我之前没有使用 using 块并且正在使用处理对象它是处理方法,但在一个类似的问题中,这解决了问题。
public static async void UpdateEventBufferFile(EventDetails EventDtls)
{
string line;
try
{
using (StreamWriter EventBufferFile = new StreamWriter(FilePath, true)) // creates the file
{
//All barcode data space sperated for split detection
line = EventDtls.SiteID + " " + EventDtls.McID + " " + EventDtls.EventID + " "
+ EventDtls.EventDT + " " + EventDtls.AdditionalInfo;
await Task.Run(() => LogFileManager.SystematicLog(" Events " + line + " added to buffer file", " BufferFileWriter.cs"));
await EventBufferFile.WriteLineAsync(line); //no need for new line char WriteLine does that
await EventBufferFile.FlushAsync();
//The using block is suffice to dispose of the object the below is no longer required
//EventBufferFile.Dispose();
//EventBufferFile.Close();
//EventBufferFile = null;
}
}
catch (Exception ex)
{
}
}
我在其他类中使用了几乎相同的方法,但不会导致相同的问题,这让我很恼火。
没有从循环中调用该方法。调用是在以下方法中的单独静态类中完成的:
public static void AddCentralEvents(int SiteID, int McID, int EventID, DateTime EventDT, string AdditionalInfo)
{
EventDetails EventDetailsObj = new EventDetails();
EventDetailsObj.SiteID = SiteID;
EventDetailsObj.McID = McID;
EventDetailsObj.EventID = EventID;
EventDetailsObj.EventDT = EventDT;
EventDetailsObj.AdditionalInfo = AdditionalInfo;
Task.Run(() => BufferFileWriter.UpdateEventBufferFile(EventDetailsObj));
}
【问题讨论】:
-
请张贴
UpdateEventBufferFile的调用站点,了解您如何使用此方法很重要。您是否有一个正在调用该方法的循环? -
为什么要重新发明轮子?使用日志框架。
-
您能否在示例控制台应用程序中重现该问题?
-
不相关:
public async static void建议为public async static Task,因为该方法不是事件处理程序。 -
为什么要在 Task.Run 中包装异步方法?
标签: c# file asynchronous