c# - C# 在 for 循环期间检查取消令牌
问题描述
我不完全理解取消令牌,但我相信这是我需要使用的。
我有一个包含文件路径的列表框和一个方法 ( 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
. 我认为问题是我正在运行其他方法的方法,我不确定是否需要应用取消检查。我得到的最接近的是它看到取消令牌的地方,但只有在一切都已经执行后才“取消”。
非常感谢任何其他建议或其他替代方法的链接。我知道我做错了很多事情。
解决方案
您必须创建一个CancellationTokenSource
,然后将其传递CancellationToken
给您要取消的方法。
private CancellationTokenSource _cts =
new CancellationTokenSource( );
public async void OnClick( object sender, EventArgs args )
{
// Disable your button here.
var token = _cts.Token;
try { await Task.Run( ( ) => LongRunning( token ), token ); }
catch( OperationCanceledException )
{
Console.WriteLine( "Task was cancelled" );
}
// Enable your button here.
}
public void OnCancel( object sender, EventArgs args )
{
_cts.Cancel( );
_cts.Dispose( );
_cts = new CancellationTokenSource( );
}
public void LongRunning( CancellationToken token = default )
{
// You can either check for cancellation
// or throw if cancelled.
// If cancellation is requested this will throw an
// OperationCanceledException.
token.ThrowIfCancellationRequested( );
// If you don't want to throw you can check the
// CancellationToken to see if cancellation was requested.
if ( token.IsCancellationRequested )
return;
// You can also pass the token to other methods that
// you want to observe cancellation.
AnotherLongRunning( token );
}
推荐阅读
- python - 如果嵌套列表中不存在元素,如何有效地检查和添加?
- powerbi - Power BI 用 0 替换(空白),没有计算列
- c++ - 从 docker image build 中省略设置文件
- json - 从端点返回数据时的最佳实践?
- github - 如何构建 devops 脚本以使用 gulp 构建和部署 github 页面?
- ionic-framework - Ionic 4 + WhatsApp 分享 - 在我分享我的信息后获取接收者/联系方式
- c - 为什么不能在数组中分配多个字符?
- vba - 如何跳过一个循环的 FOR 循环
- html - Bootstrap 4表单不发送选择框的内容
- python - 升级到 Python 3.7 后使用“python\python36”的 Pipenv 致命错误