变量线程何时安全?

时间:2014-03-11 10:36:47

标签: c# thread-safety

所以我对一个对象的线程安全有一个非常基本的问题...我不知道如何谷歌这个问题,因为它会更容易。

所以,如果我有这样的类型

public class ContainedThread
{
    private Thread _thread;
    private long _closesignal;

    private bool _isResponding = false;
    private object _isRespondingLock = new object();
    private DateTime _lastResponse = DateTime.Now;
    private object _lastResponseLock = new object();

    public ContainedThread()
    {
        _closesignal = 0;
        _thread = new Thread(new ThreadStart(this.Main));
    }

    public void Start() { _thread.Start(); }
    public void Join() { _thread.Join(); }
    public bool IsAlive { get { return _thread.IsAlive; } }
    public void Close() { _closesignal = 1; }

    public void Main()
    {
        while (Interlocked.Read(ref _closesignal) < 1)
        {
            //!Simplyfied for Stackoverflow.com!
            lock (_lastResponseLock)
            _lastResponse = DateTime.Now;
            lock (_isRespondingLock)
            _isResponding = true;
        }
    }

    public DateTime LastResponse { get { lock (_lastResponseLock) return _lastResponse; } }
    public bool IsResponding { get { lock (_isRespondingLock) return _isResponding; } }
}

如果我创建并对象,并运行Start,那么我是否足够安全地访问变量_isResponding_lastResponse?从对象内部和外部LastResponseIsResponding

我对线程和内存有点困惑,因为我猜Threads没有直接拥有内存?

0 个答案:

没有答案