Is timer (thread) discarded with monitor.tryenter or it will be executed later?

时间:2015-07-31 20:12:05

标签: c# multithreading timer monitor

I want to be sure that the following code doesn't have reentrancy. Also would like to know if threads that didn't reenter are executed later or not (I want them to be discarded). If first timer didn't finish, will the next one be immediately fired after it does finish or it will wait 15ms extra?

Thanks

public void MainFunction(IntPtr h, List<int> a)
    {
        myTimer= new System.Timers.Timer();

        myTimer.Elapsed += delegate { eventfired(h, a); };
        myTimer.Interval = 15;
        myTimer.Start();
    }
    private void eventfired(IntPtr h, List<int> a)
    {
        if (System.Threading.Monitor.TryEnter(syncThreads))
        {
            try
            {
                DoWork()

            }
            finally
            {
                System.Threading.Monitor.Exit(syncThreads);
            }
        }
    }

I'm not sure if this is the best method or autoreset= false and start timer later on the callback is better.

The point is: only one thread working at the time and discarding created threads provided that old one is still working.

1 个答案:

答案 0 :(得分:2)

This works. Use the TryEnter(ref bool) overload because it's safer in the presence of exceptions.

If first timer didn't finish, will the next one be immediately fired

Why would that be the case. The timer does not know what you are doing. It just enqueues timer ticks to the thread pool. Your TryEnter code throws collisions away.

It might happen by coincidence that multiple timer ticks execute right after another so that your code runs multiple times in succession without delay.