刚接触这个网站,所以如果我没有以可接受的方式发帖,请告诉我。
我经常按照下面的示例编写一些代码(为了清楚起见,省略了 Dispose 之类的东西。)。我的问题是,是否需要如图所示的挥发物?或者 ManualResetEvent.Set 是否像我读过的那样具有隐式内存屏障 Thread.Start 呢?或者明确的 MemoryBarrier 调用会比 volatile 更好吗?还是完全错误?此外,据我所见,某些操作中的“隐式内存屏障行为”没有记录,这很令人沮丧,在某处是否有这些操作的列表?
谢谢,汤姆
:
class OneUseBackgroundOp
{
// background args
private string _x;
private object _y;
private long _z;
// background results
private volatile DateTime _a
private volatile double _b;
private volatile object _c;
// thread control
private Thread _task;
private ManualResetEvent _completedSignal;
private volatile bool _completed;
public bool DoSomething(string x, object y, long z, int initialWaitMs)
{
bool doneWithinWait;
_x = x;
_y = y;
_z = z;
_completedSignal = new ManualResetEvent(false);
_task = new Thread(new ThreadStart(Task));
_task.IsBackground = true;
_task.Start()
doneWithinWait = _completedSignal.WaitOne(initialWaitMs);
return doneWithinWait;
}
public bool Completed
{
get
{
return _completed;
}
}
/* public getters for the result fields go here, with an exception
thrown if _completed is not true; */
private void Task()
{
// args x, y, and z are written once, before the Thread.Start
// implicit memory barrier so they may be accessed freely.
// possibly long-running work goes here
// with the work completed, assign the result fields _a, _b, _c here
_completed = true;
_completedSignal.Set();
}
}