多线程事件处理程序

时间:2011-08-31 02:49:27

标签: c# multithreading

这是我的单线程代码:

OnStart 
{
 FileSystemWatcher Watcher = new FileSystemWatcher();
 Watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite |NotifyFilters.CreationTime | NotifyFilters.DirectoryName;
 FileActionHandler ActionHandler = new FileActionHandler();
 Watcher.Created += new FileSystemEventHandler(ActionHandler.onCreate);
}

onCreate(object source,FileSystemEventArgs e)
{
 try
 {
 FileInfo file = new FileInfo (e.FullPath);
 String output = <FileName>File.Name + <FullPath>File.FullName + <FileSize>File.Length +  <CreationTime>File.CreationTime + <LastAccess>File.LastAccess + <LastWriteTime>File.LastWriteTime;
 LogToTextFile(output);
 }
 catch
 {
 LogToTextFile(ex.GetBaseException().Message);
 }
}

private void LogToTextFile(String s)
{
FileStream fileStream = new FileStream(@"c:\Log.txt", FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fileStream);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fileStream.Close();
}

问题:我想在C#中使用多线程进行事件处理? Simply,what I mean is to start a new thread to handle for each of the events raised.  我该怎么做呢?请帮我解决这个紧迫的问题...

2 个答案:

答案 0 :(得分:7)

以下是每次收到活动时创建任务的小片段,并且多线程处理事件处理程序:

Watcher.Created += new FileSystemEventHandler(onCreateMultiThreaded);

onCreateMultiThreaded(object source, FileSystemEventArgs e)
{
    Task.Factory.StartNew(() => onCreate(source, e));
}

以下是线程池解决方案的简写:

ThreadPool.QueueUserWorkItem(s => onCreate(source, e));

使用线程池将允许您每次重用线程而不是创建新线程,这将使您的应用程序更快(消除创建新线程的开销。)

答案 1 :(得分:0)

如果您没有使用.NET 4,正如Pierre-Luc所提到的那样,您可以简单地换掉他的代码:

new Thread(new ThreadStart(delegate{
    onCreate(source, e);
})).Start();

或者,如果您更愿意使用ThreadPool(我建议在这种情况下使用)...

ThreadPool.QueueUserWorkItem(delegate{ onCreate(source, e); });