Why async functions are called twice?

后端 未结 3 687
悲哀的现实
悲哀的现实 2021-01-19 00:29

I\'m using Threading timer to do some periodic job:

private static async void TimerCallback(object state)
{
        if (Interlocked.CompareExchange(ref curre         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-19 00:55

    When you use Task.WhenAll on a IEnumerable> it will return a T[] of the completed Tasks results. You need to save that variable and use it or else you will end up with the multiple enumerations like Henzi mentioned in his answer.

    Here is a solution without the unnecessarily calling of .ToList()

    private static async void TimerCallback(object state)
    {
            if (Interlocked.CompareExchange(ref currentlyRunningTasksCount, 1, 0) != 0)
            {
                return;
            }
    
            var tasksRead = Enumerable.Range(3, 35).Select(i => ReadSensorsAsync(i));
            var finshedTasks = await Task.WhenAll(tasksRead);
            var tasksRecord = finshedTasks.Where(x => x != null).Select(x => RecordReadingAsync(x));
            await Task.WhenAll(tasksRecord);
    
            Interlocked.Decrement(ref currentlyRunningTasksCount);
    }
    

提交回复
热议问题