有一个功能可以尝试扫描给定的文件夹。扫描时,用户可以使用取消按钮。但它不会取消第一次尝试的扫描,但是会在下次尝试时成功。
这是我的代码框架:
private CancellationTokenSource _tokenSource;
CallingMethod()
{
var cancelationToken = GetCancelationToken();
Task.Run(() => { MethodA(true, stringVal, cancelationToken); }, cancelationToken);
}
internal void MethodA(bool isCreateNewRequested, string directoryPath, CancellationToken token)
{
bool sucess = true;
if (isCreateNewRequested)
sucess = MethodB(directoryPath, token);
if (token.IsCancellationRequested) return;
//some more code
}
private bool MethodB(string directoryPath, CancellationToken token)
{
var fileEntries = ProcessSubDirectories(directoryPath);
var totalFileCount = fileEntries.Count;
foreach (var fileEntry in fileEntries)
{
if (token.IsCancellationRequested) break;
//dosomething here
}
if (token.IsCancellationRequested) return false;
}
private CancellationToken GetCancelationToken()
{
_tokenSource?.Cancel();
_tokenSource = new CancellationTokenSource();
return _tokenSource.Token;
}
答案 0 :(得分:0)
首先,您必须创建简单的取消令牌:
CancellationToken cToken = new CancellationToken();
就是这样。该令牌必须传递给异步方法,然后:
CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(cToken);
然后使用此cts。
if(cts.Cancelled) //written from head, so there may be other way to check it
cts.Token.ThrowIfCancellationRequested();
或:
cts.Cancel(true); //if you want to cancel manually something
cts.Token.ThrowIfCancellationRequested();
您不能只返回。您必须抛出以取消操作。