我有以下代码:
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(在lastUploadActivityTime = DateTime.Now;
期间),以防止在第二个方法(lastUploadActivityTime.AddSeconds(5) <= DateTime.Now
)中读取lastUploadActivityTime。我该怎么做? Mutex
是否帮助我阻止阅读变量?
答案 0 :(得分:1)
互斥量会过度,在两种方法中使用锁来同步读取 http://msdn.microsoft.com/en-us/library/c5kehkcz.aspx
答案 1 :(得分:1)
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);
}
}