0

I have an API which gives the data according to the time range requested.I have created an event which will call the dataInfo (gets the information about stored data) for every 2 minutes.How to stop or block the event until the current execution is completed.

following is the method where data refresh handler is set.

public async Task DataInitialize(DataProperties dataProperties)
{

    //DataInitialise method is called when the API is initialized and it gets the data information, then for every 2 minutes it raises an event to refresh the dataInfo.
     var dataInfo = GetStoredata();

    //set the datarefresh handler
    this.refreshTimer = new System.Timers.Timer { Interval = TimeSpan.FromMinutes(2).TotalMilliseconds };
    this.refreshTimer.Elapsed += async (sender, e) => await this.DataRefreshEventHandler(sender, e);
    this.refreshTimer.AutoReset = true;
    this.refreshTimer.Enabled = true;
    await Task.CompletedTask;
}

public async Task DataRefreshEventHandler(object dataUpdateTimer, ElapsedEventArgs e)
{
   var dataInfo = GetStoredata();
   await Task.CompletedTask;
}

API calls GetResponse method which uses dataInfo to retrieve the data and send the response.

public async Task<string> GetResponse(dataInfo){

 return await Task.FromResult(GetData(dataInfo));
}

if the API takes more than 2 minutes to send the response, the event will be raised and it gets different dataInfo which will make API to throw an exception.

Pooja P N
  • 57
  • 1
  • 6

2 Answers2

0

Use timeoutCancellationTokenSource to set timeout for previous task

public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout) {

    using (var timeoutCancellationTokenSource = new CancellationTokenSource()) {

        var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
        if (completedTask == task) {
            timeoutCancellationTokenSource.Cancel();
            return await task;  
        } else {
            throw new TimeoutException("time out.");
        }
    }
}
junlan
  • 302
  • 1
  • 5
0

What you need is a Queue, add stuff to the Queue use a thread safe collection.

https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent.concurrentqueue-1?view=netframework-4.8

As events come in add them to the queue and dequeue one at a time.

fkerrigan
  • 270
  • 2
  • 9