Takarii
Takarii

Reputation: 1648

Implementing a semaphore into an Async method

Consider that I have the following (very basic) method within my WCF service:

public async Task MyMethod()
{
    await Task.Run(() => 
    {
        //do stuff
    });
}

The issue I'm facing is that the code within the task searches the database, sends emails for the required records and updates a database when sent, however if the call were to be done twice in quick succession then potential duplicates could be sent.

Is it possible to implement semaphores into this method to prevent this given that the UWP app I have written would call the method asynchronously?

Upvotes: 1

Views: 1729

Answers (1)

Chrille
Chrille

Reputation: 1453

Create a private field in your class of type Mutex and protect the code like so:

private Mutex _mutex = new Mutex();
private DateTime _lastRequest = DateTime.MinValue;

...   

public async Task MyMethod()
{
    await Task.Run(() => 
    {
        _mutex.WaitOne();
        if(DateTime.Now < _lastRequest + TimeSpan.FromSeconds(3))
            return;

        _lastRequest = DateTime.Now;

        //do stuff
        _mutex.ReleaseMutext();
    });
}

Upvotes: 1

Related Questions