【发布时间】:2021-01-08 03:41:15
【问题描述】:
我不完全了解取消令牌,但我相信这是我需要使用的。
我有一个包含文件路径的列表框和一个方法 (ProcesstListSort),它遍历列表框中的每个文件路径并根据文件类型执行不同的方法。 ProcessListSort 从另一个方法调用,即从按钮单击调用。我正在尝试在后台任务中运行BeginEverything,因为它锁定了 UI。在这种情况下实施取消令牌检查的最佳位置是什么?
单击此按钮将启动该过程:
public async void button1_Click(object sender, EventArgs e)
{
Task task1 = new Task(BeginEverything);
task1.Start();
await task1;
}
哪个启动这个:
public void BeginEverything()
{
CreateThing1();
CreateThing2();
ProcessListSort(); //This is the one I think I need to interrupt because it's the longest
CreateThing3();
CreateThing4();
}
在此处启动最长的任务(根据文件类型对文件进行排序并执行其他方法,将文件路径传递给其他方法):
public void ProcessListSort()
{
for (int i = 0; i < listBox2.Items.Count; i++)
{
string p = listBox2.Items[i].ToString();
FileAttributes attr = File.GetAttributes(p);
if (p.EndsWith(".zip"))
{
Method1(p);
}
if (p.EndsWith(".txt"))
{
Method2(p);
}
if ((attr & FileAttributes.Directory) == FileAttributes.Directory)
{
Method3(p);
}
else
{
Method4(p);
}
}
}
单击取消按钮后立即取消是理想的,但我会满足于在ProcessedListSort 中处理的每个文件之间取消。我认为问题是我正在运行其他方法的方法,我不确定是否需要应用取消检查。我得到的最接近的是它看到取消令牌的地方,但只有在一切都已经执行后才“取消”。
非常感谢任何其他建议或替代方法的链接。我知道我做错了很多事情。
【问题讨论】:
-
看起来它可以工作,但它与我所拥有的并没有那么顺利,我一直遇到问题 - 我确定只是因为我不知道我在做什么.
标签: c# winforms for-loop cancellation cancellation-token