Asynchronous Multiple Tasks in C# windows service ( with two different await times )

1.9k views Asked by At
public Class Config
{
  public string Name;
  public string Interval;
}

I have List Of Tasks Coming from database

List<Config> configList = new List<Config>();

Every task coming from database will have Name and Interval

for example say i have two items in list with following data

  1. Name is X and Interval is 2 mins
  2. Name is Y and Interval is 4 mins

Now I need a windows service, where i want to run or execute Task X for every 2 mins, Tasks Y for every 4 mins in asynchronous manner.

I know that, we have to use Polling.

I managed to poll database for every 'XXX' mins (eg 5 mins) by googling out but am unable to run two tasks with two different intervals in asynchronous manner.

for every poll, i have to run two tasks and for 1st task i need to wait for 2 mins before the next poll begins and for 2nd task i need to wait for 4 mins before the next poll begins and that too in asynchronous manner. please help.

Update -1

Am using the following code to poll database for every 2 mins

private Task _proccessTask;
private CancellationTokenSource _cancellationTokenSource;

protected override void OnStart(string[] args)
{
    _cancellationTokenSource = new CancellationTokenSource();
    _proccessTask= Task.Run(() => DoWorkAsync(_cts.Token));
}

protected override void OnStop()
{
    _cancellationTokenSource.Cancel();
    try
    {
        _proccessTask.Wait();
    }
    catch (Exception e)
    {
        // handle exeption
    }
}
public async Task DoWorkAsync(CancellationToken token)
{
    while (true)
    {
        try
        {
            ProccessTaskX();
        }
        catch (Exception e)
        {
            // Handle exception
        }
   //able to poll database for every 2 mins in async manner if i have 1 task

      await Task.Delay(TimeSpan.FromMinutes(2), token);

    }
}

Now I want to Run or execute list of 2 tasks with two different intervals i.e TaskX for every 2 mins and TaskY for every 4 mins and both tasks should run in asynchronous manner, thanks in advance, please help.

0

There are 0 answers