假设我有一个多线程ForEach我想每个循环都将Console.WriteLine()转换成一个文件,我发现单线程的例子是这样的:
('DATABASE2',)
(000000000000,)
(000000000000,)
('DATABASE1',)
(000000000000,)
(000000000000,)
('DATABASE3',)
现在对于多线程我尝试过类似的事情:
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
try
{
ostrm = new FileStream("C:\\Users\\Public\\Documents/Redirect.txt", FileMode.OpenOrCreate, FileAccess.Write);
writer = new StreamWriter(ostrm);
}
catch (Exception e)
{
Console.WriteLine("Cannot open Redirect.txt for writing");
Console.WriteLine(e.Message);
return;
}
Console.SetOut(writer);
但是这样在每个文件中写入的内容都不是预期的,并且多线程看起来没有正确处理。怎么解决这个问题?