我想要同时处理几千个目录。不幸的是,我对C#中的MultiThreading几乎没有经验。
我有:
实现观察者模式的logger类,在Service中添加LogMessage时通知我的表单。 带有listView的表单,在记录消息时收到通知,应该将消息添加到listView 我交给日志对象的服务
public partial class BrowseFolderForm : Form, ILogObserver
{
private IndexerService indexerService;
private MessageLogger log;
private static object syncLock = new object();
public BrowseFolderForm(){
log = new MessageLogger(this);
indexerService = new IndexerService(log);
}
// Implementation of the logger classes observer callback interface
public void NotifyChanges(Logger.Message m){
lock (syncLock)
{
// add message m to the UltraListViewItem
}
}
public void startIndexing(){
using (var finished = new CountdownEvent(1))
{
foreach (ObservedDirectory obsDir in dirs)
{
var capture = obsDir;
finished.AddCount();
ThreadPool.QueueUserWorkItem(
(state) =>
{
try
{
indexerService.StartIndexingModels(capture);
}
finally
{
//prgURLIndexing.Value = i++;
finished.Signal(); // Signal that the work item is complete.
}
}, null);
}
finished.Signal(); // Signal that queueing is complete.
finished.Wait(); // Wait for all work items to complete.
MessageBox.Show("The task finished successfully.");
}
}
}
问题是,在NotifyChanges方法中,我仍然收到一个错误,即Control无法从另一个线程访问。我该怎么办?