I want to create an array of Tasks, called listTask, with each element of listTask is a Task of type A, Task of type A is created by the function Task.WhenAll. then I do await Task.WhenAll(listTask) But the program does not perform the work in the listTask array. I set debug and those tasks were completed, I don't understand why
namespace Ding.LearningNewThings
{
public class MultiChannelTask
{
public static async Task RunMiltipleChannel()
{
ConcurrentDictionary<int, Channel<Position>> _dataChannels = new ConcurrentDictionary<int, Channel<Position>>();
var listPlace = Place.InitData();
var numberOfPlace = listPlace.Count();
for (int i = 0; i < listPlace.Count(); i++)
{
_dataChannels.TryAdd(i, Channel.CreateUnbounded<Position>());
}
Task[] listStationTask = new Task[numberOfPlace];
for (var j = 0; j < numberOfPlace; j++)
{
var listTask = new Task[2];
var placeOuter = listPlace[j];
listTask[0] = Task.Run(async () =>
{
int IndexOfPlace = j;
var place = new Place()
{
ID = placeOuter.ID,
Name = placeOuter.Name
};
Channel<Position> dataChannel;
var r = new Random();
if (_dataChannels.TryGetValue(IndexOfPlace, out dataChannel))
{
var position = new Position()
{
PlaceID = place.ID,
PlaceName = place.Name,
ID = r.Next(1, 100)
};
await dataChannel.Writer.WriteAsync(position);
Console.WriteLine($"Push postion ID {position.ID}, Place ID {position.PlaceID}");
}
});
listTask[1] = Task.Run(async () =>
{
var IndexOfPlace = j;
Channel<Position> dataChannel;
var r = new Random();
if (_dataChannels.TryGetValue(IndexOfPlace, out dataChannel)) {
var position = await dataChannel.Reader.ReadAsync();
Console.WriteLine($"Get postion ID {position.ID}, Place ID {position.PlaceID}");
}
});
listStationTask[j] = Task.WhenAll(listTask);
}
await Task.WhenAll(listStationTask);
}
}
public class Place
{
public int ID { get; set; }
public string Name { get; set; }
public static List<Place> InitData()
{
var listData = new List<Place>();
for (int i = 0; i < 10; i++)
{
var data = new Place()
{
ID = i,
Name = $"Postion{i}",
};
listData.Add(data);
}
return listData;
}
}
public class Position
{
public int ID { get; set; }
public int PlaceID { get; set; }
public string PlaceName { get; set; }
public string Name { get; set; }
public static List<Position> InitData()
{
var listData = new List<Position>();
for (int i = 0; i < 10; i++)
{
var data = new Position()
{
ID = i,
Name = $"Postion{i}"
};
listData.Add(data);
}
return listData;
}
}
}
I seem the task have had done ahead of intended. Sometimes it works, but I don't know why the job always completes without running in the list task code.