gpt4 book ai didi

c# - 多线程锁定读/写文本c#

转载 作者:太空狗 更新时间:2023-10-29 23:49:40 24 4
gpt4 key购买 nike

经过大量研究,阅读并尝试了此处的所有问题后,我认为是时候寻求帮助了。

我有一个用 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))

我尝试了很多东西,关闭文件等,但是当线程同时开始工作时,程序停止并给我错误 进程无法访问文件,因为它正在使用中( self 解释)。但我不明白为什么,这个锁是假设阻止另一个线程进入这里。而且我使用同步方法来编写线程安全的。很抱歉写了这么长,这是我在这里的第一篇文章。

最佳答案

synchronized writer 仍然应该被释放:

var newline = w + " - test";
using (var sw = new StreamWriter(path_file))
using (var sync = TextWriter.Synchronized(sw))
{
// no need to add a new line char, just use other method to write
sync.WriteLine(txt + newline);
}

此外,您还可以保存一个sync 变量并从所有线程调用它的方法,它会为您完成所有工作,您可以稍后在编写完所有文本后处理它。

关于c# - 多线程锁定读/写文本c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42009097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com