V
V
vilix2016-05-19 04:44:47
C++ / C#
vilix, 2016-05-19 04:44:47

What is the best way to wait (check) the execution of the function (Monitor.Enter vs While(var))?

Hello everyone, when writing a WCF service, the following task arose for me: there is a method1 that can be executed for a long time, it can be called from any instance, but it is required that this method can be only one in operation. I solved this part with isBusy=true at the beginning and isBusy=false at the end. This part works.
A self-hosted console application periodically calls some methods that should not be executed at the same time as method1. That is, if method1 is executed, then we wait until it finishes and then run these methods. And then I thought about what is better to use and is there any difference at all, or wait until isBusy=true. Or create busyLock.
Below is an example of a test application that does what I need with two different methods.

static bool isBusy = true;
        static object busyLock = new object();

        static void Main(string[] args)
        {
            new Task(longTaks1).Start();
            while (isBusy) { }
            taskMustRunOnlyWhenLongTaskNotRunning();

            new Task(longTaks2).Start();
            Monitor.Enter(busyLock);
            taskMustRunOnlyWhenLongTaskNotRunning();

            Console.ReadLine();
        }

        static void taskMustRunOnlyWhenLongTaskNotRunning()
        {
            Console.WriteLine("taskMustRunOnlyWhenLongTaskNotRunning");
        }

        static void longTaks1()
        {
            isBusy = true;
            Thread.Sleep(5000);
            isBusy = false;
        }

        static void longTaks2()
        {
            Monitor.Enter(busyLock);
            Thread.Sleep(5000);
            Monitor.Exit(busyLock);
        }

The question is rather whether there is a significant difference in approaches and what are the pitfalls. Thanks for answers.
PS isBusy on the service I store in the thread-safe singleton field.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Peter, 2016-05-19
@vilix

Use Event for this. Threw off the signal state, the service is busy.
For your task, ManualResetEvent is better. The service completed the task and set the signaled state itself.
In other threads, you will simply write
If there is no signaled state, your thread will sleep for the right time and wake up when the service exits and sets the signaled state or when the timeout expires.

D
Dmitry Eremin, 2016-05-19
@EreminD

not through lock ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question