【发布时间】:2017-06-19 22:20:03
【问题描述】:
经过大量研究,阅读并尝试了这里的所有问题后,我认为是时候寻求帮助了。
我有一个 C# 应用程序,我正在尝试使用不同的线程写入相同的文件。
public static void LaunchThreads(string path_file)
{
int i = 0;
Dictionary<int, Thread> threadsdico = new Dictionary<int, Thread>();
while (i < MAX_THREAD)
{
Thread thread = new Thread(() => ThreadEntryWriter(string path_file));
thread.Name = string.Format("ThreadsWriters{0}", i);
threadsdico.Add(i, thread);
thread.Start();
i++;
}
int zz = 0;
while (zz < threadsdico.Count())
{
threadsdico[zz].Join();
zz++;
}
}
private static readonly Object obj = new Object();
public static void ThreadEntryWriter(string path_file)
{
int w = 0;
while (w < 99)
{
string newline = w + " - test" + "\r";
lock(obj)
{
string txt = File.ReadAllText(path_file);
using (TextWriter myWriter = new StreamWriter(path_file))
{
TextWriter.Synchronized(myWriter).Write(txt + newline);
}
}
w++;
}
}
我已经尝试了所有方法,我的代码在全局范围内都是这样的,但是我尝试了所有方法,每个锁,每个文件打开方法,但我不断收到The process cannot access the files because it's in use。产生此错误的行是using (TextWriter myWriter = new StreamWriter(path_file))。
我尝试了很多东西,关闭文件等,但是当线程同时开始工作时,程序停止并给我错误The process cannot access the files because it's in use(自我解释)。但我不明白为什么,锁是为了阻止另一个线程进入这里。我使用同步方法来编写线程安全的。抱歉写了这么长,这是我在这里的第一篇文章。
【问题讨论】:
-
"程序停止并给我错误。" - 你能分享你的错误吗?
-
您确定没有其他代码可以打开该文件吗?如果是,请关闭防病毒扫描程序并重试。
-
错误类似于“进程无法访问文件,因为它正在使用中”。
-
TextWriter.Synchronized返回一个新实例(原始 TextWriter 的包装器)。也许你也需要Dispose那个实例? -
是本地文件还是网络共享文件?顺便说一句,我试图重现这个问题,但我的程序在 MAX_THREAD=10 时运行良好。 (只需添加主函数包装器)
标签: c# multithreading c#-4.0 thread-safety locking