我有一个数据列表,想要创建与列表中元素数量相对应的任务数量。但我不知道如何正确完成频道。
我的代码,但通道没有像我预期的那样关闭。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Channels;
using System.Threading.Tasks;
namespace Ding.LearningNewThings
{
public class MultipleChannel
{
public static async Task RunMiltipleChannel()
{
List<Place> listPlace = Place.InitData();
Channel<Position> _dataChannel = Channel.CreateUnbounded<Position>();
var listTask = new Task[11];
var listStatus = new bool[10];
for (int k = 0; k < listPlace.Count(); k++)
{
var place = listPlace[k];
listTask[k] = Task.Run(async () =>
{
int kk = k;
int count = 0;
Random r = new Random();
while (count < 10)
{
int id = r.Next(1, 1000);
var position = new Position()
{
ID = id,
Name = $"Postion{id}",
PlaceID = place.ID,
PlaceName = place.Name
};
Console.WriteLine($"WRITE: Position ID: {position.ID}, Postion Name: {position.Name}");
await _dataChannel.Writer.WriteAsync(position);
count++;
}
lock (listStatus)
{
if(count == 10)
{
listStatus[k] = true;
}
bool isStop = true;
foreach(var status in listStatus)
{
if (!status)
{
isStop = false;
}
}
if (isStop)
{
_dataChannel.Writer.Complete();
Console.WriteLine("Stopped");
}
}
});
}
listTask[10] = Task.Run(async () =>
{
while (await _dataChannel.Reader.WaitToReadAsync())
{
await Task.Delay(100);
var data = await _dataChannel.Reader.ReadAsync();
Console.WriteLine($"READ: Position ID: {data.ID}, Postion Name: {data.Name}");
}
});
await Task.WhenAll(listTask);
}
}
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;
}
}
}
如果我想为每个任务创建单独的频道,我该如何完成它们?请给我一个例子。