开发者

Different thread share an object

I have this following code fragment which is accessed by different threads.

         try
         {            
            this.RefreshSettings();
            DateTime lastChecked = DateTime.Now.AddMilliseconds(-1 * m_Settings.Interval);

            while (Run)
            {
                if ((DateTime.Now - lastChecked).TotalMilliseconds >= this.m_Settings.Interval)
                {
                    lastChecked = DateTime.Now;

                    if (this.ShouldNotify())
                    {
                        object LockObj = new object();

                        lock (LockObj)
                        {
                            this.Notify();
                        }
              开发者_开发技巧      }
                }
                //Thread.Sleep(this.m_Settings.Interval);
            }
         }

As you can see, I only want ShouldNotify() method to be called after every given interval of time (m_settings.Interval). However, my problem is if two or more threads have called NotifyIfNecesarry function, they are sharing the lastChecked variable. So, if one thread resets its value to dateTime.Now, it gets reset for the others too.

How can I write that method so that each thread maintains its own lastChecked? Using Thread.Sleep is not an option because when the value of the bool Run is changed to false, I need the loop to exit instantaneously. If I have a thread.Sleep, and the thread is sleeping, the program won't exit until it checks the while condition, so there is a possible mak delay of m_settings.Interval.


You should skip your loop and use for example System.Timers.Timer. And your lock is also out of place. It should created outside the loop and not per instance. When using a lock all threads must lock on the same object.


Why don't you simply use a timer object?

Either: System.Windows.Forms.Timer Or: System.Threading.Timer


It doesn't make any sense to lock on a locally created object. All the threads must lock on the same instance, otherwise there will be no synchronization.

The code below doesn't work as intended, as all the threads running this code will have their own local reference to a newly created instance of object.

object LockObj = new object();

lock (LockObj)
{
   this.Notify();
}

Also, since lastChecked is a local value type, each thread will have its own copy.


How can I write that method so that each thread maintains its own lastChecked

You've already done this.

Coding Gorilla had it right.

The lastChecked variable is local...Local variables are not shared between threads

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜