Thread safety is not so much important when you instance classes and use their methods to start the thread correcT?
Asked
Active
Viewed 238 times
0
-
Not sure if this would help, but check out an answer I posted here: http://stackoverflow.com/questions/5187568/delays-when-reading-process-output-asynchronously/5187715#5187715 – Jesse C. Slicer Jul 26 '11 at 15:24
1 Answers
0
If multiple threads are accessing the same object instance, then you need to add locking to ensure thread safety:
// 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;
}
};
As a side note, if you are using .NET 4, you might want to check the ConcurrentQueue class. It's a thread safe implementation of a FIFO buffer, which can be useful if multiple threads need to enqueue their items simultaneously:
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);
}
};
To dequeue items in a separate thread, you would use:
SomeData data = null;
while (_queue.TryDequeue(out data))
{
// do something with data
}
Groo
- 47,804
- 16
- 116
- 191
-
Multiple threads are not accessing the same object. Creating an instance of a class that starts the processes for each thread. – Joey Gfd Jul 26 '11 at 14:08
-
-
@Joey: add this to the event handler: `Console.WriteLine(System.Threading.Thread.CurrentThread.ManagedThreadId);`. I believe that you should get different thread IDs written to console. – Groo Jul 26 '11 at 14:18
-
I ran the executable four times and here was the status throughout: Got 15 15 7 15 (First program output caputured successful, Then second program output not captured) then 15 15 15 15 (first program output captured succesful, then second program output not captured). Not sure what this means? – Joey Gfd Jul 26 '11 at 14:30