Thread safe StreamWriter C # como fazê-lo? 2
Portanto, esta é uma continuação da minha última pergunta - Então, a pergunta era "Qual é a melhor maneira de criar um programa que é seguro para threads, em termos de que ele precisa gravar valores duplos em um arquivo. Se a função que salva os valores via streamwriter está sendo chamado por vários threads? Qual é a melhor maneira de fazer isso? "
E eu modifiquei algum código encontrado no MSDN. Que tal o seguinte? Este grava tudo corretamente no arquivo.
namespace SafeThread
{
class Program
{
static void Main()
{
Threading threader = new Threading();
AutoResetEvent autoEvent = new AutoResetEvent(false,);
Thread regularThread =
new Thread(new ThreadStart(threader.ThreadMethod));
regularThread.Start();
ThreadPool.QueueUserWorkItem(new WaitCallback(threader.WorkMethod),
autoEvent);
// Wait for foreground thread to end.
regularThread.Join();
// Wait for background thread to end.
autoEvent.WaitOne();
}
}
class Threading
{
List<double> Values = new List<double>();
static readonly Object locker = new Object();
StreamWriter writer = new StreamWriter("file");
static int bulkCount = 0;
static int bulkSize = 100000;
public void ThreadMethod()
{
lock (locker)
{
while (bulkCount < bulkSize)
Values.Add(bulkCount++);
}
bulkCount = 0;
}
public void WorkMethod(object stateInfo)
{
lock (locker)
{
foreach (double V in Values)
{
writer.WriteLine(V);
writer.Flush();
}
}
// Signal that this thread is finished.
((AutoResetEvent)stateInfo).Set();
}
}
}