2011-07-26 79 views
0

当您实例化类并使用它们的方法启动线程correcT时,线程安全性并不那么重要?什么时候线程安全问题?

+0

什么信息的类型是什么? –

+0

请参阅编辑。 –

+0

不知道这是否会有所帮助,但检查出我在这里发布的答案:http://stackoverflow.com/questions/5187568/delays-when-reading-process-output-asynchronously/5187715#5187715 –

回答

0

如果多个线程访问相同的对象实例,那么你需要添加锁定以保证线程安全:

// make sure that this is defined *outside* the method 
// so that all threads lock on the same instance 
private readonly object _lock = new object(); 

... 

// add a lock inside your event handler 
proc.OutputDataReceived += (object sendingProcess, DataReceivedEventArgs e) => 
{ 
    if (e.Data != null) 
    { 
     lock (_lock) 
      info.additional += e.Data; 
    } 
}; 

作为一个侧面说明,如果你使用的是.NET 4,你可能要检查类ConcurrentQueue。这是一个线程安全的实现FIFO缓冲器,如果多个线程需要同时排队的项目可以是有用的:

private ConcurrentQueue<SomeInfo> _queue = new ConcurrentQueue<SomeInfo>(); 

... 

proc.OutputDataReceived += (object sendingProcess, DataReceivedEventArgs e) => 
{ 
    if (e.Data != null) 
    { 
     // no need to lock 
     _queue.Enqueue(e.Data); 
    } 
}; 

要在一个单独的线程出列的项目,你可以使用:

SomeData data = null; 
while (_queue.TryDequeue(out data)) 
{ 
    // do something with data 
} 
+0

多个线程不访问同一个对象。创建一个启动每个线程进程的类的实例。 –

+0

队列不是问题。这是我相信的输出重定向。 –

+0

@Joey:将此添加到事件处理程序:'Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);'。我相信你应该得到不同的线程ID写入控制台。 – Groo

相关问题