读取块变量

block variable for read

我有以下代码:

private DateTime lastUploadActivityTime = DateTime.Now;
private void HttpSendProgress(object sender, HttpProgressEventArgs e)
{
    // update variable
    lastUploadActivityTime = DateTime.Now;
    ......
    boolThreadAvailableTargetSiteActive = false;
}

// this method is executed in different thread, than method above
private void ThreadCheckAvailableTargetSite()
{
    while (boolThreadAvailableTargetSiteActive)
    {
        if (lastUploadActivityTime.AddSeconds(5) <= DateTime.Now)
        {
            MessageBox.Show("BREAK");
            boolThreadAvailableTargetSiteActive = false;
        }
        Thread.Sleep(500);
    }
}

我需要在第一种方法(lastUploadActivityTime = DateTime.Now; 期间)阻止变量 lastUploadActivityTime 以防止在第二种方法(lastUploadActivityTime.AddSeconds(5) <= DateTime.Now)中读取 lastUploadActivityTime。我该怎么做? Mutex 可以帮助我防止读取变量吗?

mutex 太过分了,在这两种方法中都使用 lock 来同步读取 http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx

lock关键字确保一个线程不会进入代码的临界区,而另一个线程在临界区。如果另一个线程试图输入锁定的代码,它将等待、阻塞,直到对象被释放。最佳做法是定义要锁定的私有对象,或定义私有静态对象变量以保护所有实例共有的数据。

private object syncLock = new object();
private DateTime lastUploadActivityTime = DateTime.Now;
private void HttpSendProgress(object sender, HttpProgressEventArgs e)
{
    // update variable
    lock (syncLock)
    {
       lastUploadActivityTime = DateTime.Now;
    }
}

// this method is executed in different thread, than method above
private void ThreadCheckAvailableTargetSite()
{
    while (boolThreadAvailableTargetSiteActive)
    {
        lock (syncLock)
        {
           if (lastUploadActivityTime.AddSeconds(5) <= DateTime.Now)
           {
               MessageBox.Show("BREAK");
               boolThreadAvailableTargetSiteActive = false;
           }
        }
        Thread.Sleep(500);
    }
}