我有一个带有三个按钮的 Windows 窗体。一个按钮将条目添加到 BlockingCollection。一个开始处理列表,一个停止处理列表。
我可以将条目添加到我的 BlockingCollection 中,当我单击 Start 时,列表会按照我的预期使用。我仍然可以添加新项目,并且它们会继续被消耗。但是,当我单击停止按钮时,虽然任务确实停止了,但我无法使用开始按钮再次启动它们。
我在取消任务时做错了什么,他们不会重新开始?我已经阅读了无数关于取消任务的项目,但仍然没有“明白”。
任何帮助都会很棒。这是代码...
// Blocking list for thread safe queuing
private BlockingCollection<QueueItem> ItemList = new BlockingCollection<QueueItem>();
private CancellationTokenSource CancelTokenSource = new CancellationTokenSource();
private int MaxConsumers = 3;
// Form initialisation
public MainForm()
{
InitializeComponent();
}
// Create an async consumer and add to managed list
private void CreateConsumer(int iIdentifier)
{
Task consumer = Task.Factory.StartNew(() =>
{
foreach (QueueItem item in ItemList.GetConsumingEnumerable())
{
Console.WriteLine("Consumer " + iIdentifier.ToString() + ": PROCESSED " + item.DataName);
Thread.Sleep(894);
if (CancelTokenSource.IsCancellationRequested)
break; // Cancel request
}
}, CancelTokenSource.Token);
}
// Add a new item to the queue
private void buttonAdd_Click(object sender, EventArgs e)
{
for (int i = 0; i < 10; i++)
{
Task.Factory.StartNew(() =>
{
// Add an item
QueueItem newItem = new QueueItem(RandomString(12));
// Add to blocking queue
ItemList.Add(newItem);
});
}
}
// Start button clicked
private void buttonStart_Click(object sender, EventArgs e)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
// Create consumers
for (int i = 0; i < MaxConsumers; i++)
{
CreateConsumer(i);
}
}
// Stop button clicked
private void buttonStop_Click(object sender, EventArgs e)
{
CancelTokenSource.Cancel();
buttonStop.Enabled = false;
buttonStart.Enabled = true;
}
// Generate random number
private static Random random = new Random((int)DateTime.Now.Ticks);
private string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}