After a lot of research, and after reading and trying all of the questions on here, I think it's time for me to ask for some help.
I have an application in C#, and I'm trying to write in the SAME file with different thread.
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++;
}
}
I've try everything, my code is globally like that, but I've try every way, with every lock, every file open method, but I keep getting The process cannot access the files because it's in use
. The line who generate this error is this one using (TextWriter myWriter = new StreamWriter(path_file))
.
I tried a lot of thing, closing the files etc, but when threads start to work at the same time, the program stop and give me the error The process cannot access the files because it's in use
(self-explain). But I don't understand why, the lock is suppose to block another thread to enter here. And I used Synchronized method to write which is thread safe. Well sorry for the long writing it's my first post here.