I have a scenario where I have two threads - main and worker (producer/consumer) The main thread creates the worker and waits for its termination. After completion the main thread wants to access the result of the worker.
private object result;
private Exception exception;
public object Connect(int timeout)
{
Thread thread = ThreadHelper.StartNewBackground("Worker Thread", ConnectImpl);
if(!thread.Join(timeout))
throw new TimeoutException(string.Format("Connecting to the remote device has timed out ");
if (exception != null)
throw new ConnectFailedException(exception);
return result;
}
private void ConnectImpl()
{
try
{
result = ConnectToARemoteDevice();
}
catch(Exception ex)
{
exception = exc;
}
}
I am not sure about the synchronization of the results (result and exception field). In my opinion there is a possibility that the main thread does not see the updaed values. Therefore I would reimplement ConnectImpl() into:
private void ConnectImpl()
{
try
{
Interlocked.Exchange(ref result, ConnectToARemoteDevice());
}
catch(Exception ex)
{
Interlocked.Exchange(refexception, ex);
}
}
Or maybe I am wrong and it is not necessary? I am not sure if this necessary because for the following snippet run with optimization it does not run undefinetly:
bool complete = false;
var t = new Thread (() =>
{
complete = true;
});
t.Start();
t.Join(); // comment this line to run undefinetly
bool toggle = false;
while (!complete) toggle = !toggle;
complete = true;
Is Join making some MemoryBarrier? I am using .NET 3.5 so I cannot use TPL, but maybe you can suggest another mechanism/implementation?
Solved Are memory-barriers required when joining on a thread? Join is making a MemoryBarrier.