tuc*_*aff 5 c# multithreading locking thread-safety c#-4.0
经过大量的研究,在阅读并尝试了所有问题后,我认为是时候向我寻求帮助了.
我在C#中有一个应用程序,我正在尝试使用不同的线程在SAME文件中编写.
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++;
}
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了所有的东西,我的代码是全局的,但是我已经尝试了各种方法,每个锁,每个文件打开方法,但我一直在努力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
(自我解释).但我不明白为什么,锁定是为了阻止另一个线程进入这里.我使用Synchronized方法编写线程安全的.很抱歉长篇大论是我在这里的第一篇文章.
同步写入器仍然应该被处理:
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);
}
Run Code Online (Sandbox Code Playgroud)
另外,您可以保存一个sync
变量并从所有线程调用它的方法,它会为您完成所有工作,并且您可以在编写完所有文本后处理它。
归档时间: |
|
查看次数: |
737 次 |
最近记录: |