0

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.

barteloma
  • 6,403
  • 14
  • 79
  • 173
  • 1
    You are awaiting StartAccessTokenTimer(), until it returns, its not going to call StartItemsTimer(), also I see no break for your while loop so its going to continue awaiting StartAccessTokenTimer() to return – Ryan Wilson May 10 '18 at 12:12
  • Updates? Refreshes you mean? Isn't it a bit wasteful to have a loop just sit updating the token? – ProgrammingLlama May 10 '18 at 12:20
  • Yes refreshes toke, I will update the post. – barteloma May 10 '18 at 12:22
  • Couldn't you just refresh the token when you try to make a request but get a 401 back (instead of this application-long loop)? – ProgrammingLlama May 10 '18 at 12:24
  • 2
    do you want to do `await Task.WhenAll(StartAccessTokenTimer(),StartItemsTimer())` with some additional synchronization of variables? – Dmitry Pavliv May 10 '18 at 12:28
  • There's no block in this code. Your `StartAccessTokenTimer` never exits, it keeps refreshing the token. `await` doesn't make anything run in asynchronously, it *awaits* for an asynchronous operation to finish, then continues execution. Something I've already posted as a comment in your *previous* question. – Panagiotis Kanavos May 10 '18 at 12:29
  • 1
    What do you want to actually do? If the token is refreshed, are you going to keep refreshing? In this case why not get the token before every call to `GetItems`? All previous tokens will be wasted – Panagiotis Kanavos May 10 '18 at 12:32
  • @PanagiotisKanavos access token expires in 60 seconds. So I will refresh it every 60 sec. But I am getting items every 3 seconds. I wil do this. – barteloma May 10 '18 at 12:40

1 Answers1

1

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()
    });
} 
bman7716
  • 693
  • 7
  • 14