barteloma
barteloma

Reputation: 6855

C# Task.Delay blocks second task

I want to run two tasks.

StartAccessTokenTimer() runs every 60 seconds and refreshes accesstoken variable. StartItemsTimer() will start after StartAccessTokenTimer() and work every 3 seconds if access token get.

    private accessToken = "";

    private async Task StartAccessTokenTimer()
    {
        CancellationTokenSource source = new CancellationTokenSource();

        while (true)
        {
            accesstoken = await GetAccessToken();
            await Task.Delay(TimeSpan.FromSeconds(3), source.Token);
        }
    }

    private async Task StartItemsTimer()
    {
        CancellationTokenSource source = new CancellationTokenSource();

        while (true)
        {
            var items = await GetItems(accessToken, "1");
            await Task.Delay(TimeSpan.FromSeconds(60), source.Token);
        }
    }

    public async Task StartOperations(){
        await StartAccessTokenTimer();
        await StartItemsTimer();
    }

But it does not filre GetItems() methot. Because StartAccessTokenTimer() never start.. It fires GetAccessToken() continiously.

Upvotes: 0

Views: 112

Answers (1)

bman7716
bman7716

Reputation: 713

To trigger them to fire at the same time you can do the following:

public async Task StartOperations()
{
    await Task.WhenAll(new Task[] 
    {
        StartAccessTokenTimer(),
        StartItemsTimer()
    });
} 

Upvotes: 1

Related Questions