我有一个名为Load的UI按钮.它产生一个线程,反过来产生一个任务.任务等待,如果过期,任务将被取消."加载"按钮未禁用,用户可以多次单击它.每次单击时,都应取消上一个任务.
我对如何在这里使用CancellationTokenSource和CancellationToken感到困惑.下面是代码.您能否建议如何使用它以及以下用法是否有任何问题?请不要异步,因为我们还没有.
CancellationTokenSource _source = new CancellationTokenSource();
public void OnLoad()
{
//Does this cancel the previously spawned task?
_source.Cancel();
_source.Dispose();
_source = new CancellationTokenSource();
var activeToken = _source.Token;
//Do I need to do the above all the time or is there an efficient way?
Task.Factory.StartNew(() =>
{
var child = Task.Factory.StartNew(() =>
{
Thread.Sleep(TimeSpan.FromSeconds(20));
activeToken.ThrowIfCancellationRequested();
}, activeToken);
if (!child.Wait(TimeSpan.FromSeconds(5)))
{
_source.Cancel();
}
});
}
Run Code Online (Sandbox Code Playgroud)
注意我需要取消任何以前生成的任务,并且每个生成的任务都应该超时.
我熟悉 C#,但完全不熟悉 VB,我想将 C# 示例(在 LINQPad 中)转换为 VB:
if (2 + 2 == 4)
"True".Dump();
Run Code Online (Sandbox Code Playgroud)
我想出了以下工作 VB 代码:
Dim word = "True"
If 2 + 2 = 4 Then
word.Dump
End If
Run Code Online (Sandbox Code Playgroud)
现在,为什么我不能只写以下内容呢?
If 2 + 2 = 4 Then
"True".Dump ' BC30035 Syntax error
End If
Run Code Online (Sandbox Code Playgroud)
似乎我无法将方法应用于 VB 中的文字,我必须事先将其存储在变量中,但我肯定在这里遗漏了一些东西......不是吗?
PS 字符串周围的括号不起作用。