How to limit yourself to one method call at a time?

I would like to know how to implement the following restriction: one method in my Windows service should not be called again before the previous call is completed. This method goes through a couple of database tables, and it is very important that this process is not called again until it completes. I have a parameter that determines how often my service activates and under normal circumstances it never activates before the previous call was completed (because the whole process should not take more than two minutes, and the interval should be 10 minutes), but this is not so of course. I think so.

How to implement this?

+5
source share
7 answers

Mutex Semaphor e, , Mutex/Semaphore. , , , / .

+11

:

private readonly object myLock = new object();

private void MyMethod()
{
   lock(myLock)
   {
      //code goes here
   }
}

, , .

+4

Mutex, . ( using System.Transactions):

using(TransactionScope scope = new TransactionScope())
{
    try 
    {
        /* ... your current code here */
        scope.Complete();
    }
    catch (Exception e)
    {
        /* Any appropriate error handling/logging here */
    }
    finally
    {
    }
}

. , , . , TransactionsScope.

+2

, , , IPC .

+1

:

  • , Monitor.TryEnter / , .
  • ( , ) "".
  • , , , .

, .

+1

... ?

0

, :

  • ContextBoundObject
  • [].

CLR . , .

0

All Articles