当用户调整窗口大小时应该更新一些长文本,但是如果线程已经运行,应该停止并使用新的宽度参数重新开始。取消线程并重新启动它
int myWidth;
private CancellationTokenSource tokenSource2 = new CancellationTokenSource();
private CancellationToken ct = new CancellationToken();
void container_Loaded(object sender, RoutedEventArgs e)
{
ct = tokenSource2.Token;
MyFunction();
}
void container_SizeChanged(object sender, SizeChangedEventArgs e)
{
if (tokenSource2.Token.IsCancellationRequested)
MyFunction();
else
tokenSource2.Cancel();
}
void MyFunction()
{
myWidth = GetWidth();
Task.Factory.StartNew(() =>
{
string s;
for (int i=0;i<1000,i++){
s=s+Functionx(myWidth);
ct.ThrowIfCancellationRequested();
}
this.Dispatcher.BeginInvoke(new Action(() => {
ShowText(s);
}));
},tokenSource2.Token)
.ContinueWith(t => {
if (t.IsCanceled)
{
tokenSource2 = new CancellationTokenSource(); //reset token
MyFunction(); //restart
};
});
}
现在发生的事情是,当我调整窗口,我看到的文字反复地更新下一个几秒钟,就好像老线程没有取消。我究竟做错了什么?
你从来没有真正取消线程。每个调整大小增量开始另一个任务。 –
你说得对。在我看来,我能做的唯一事情就是让这些众多对象中的每一个都有一个全局任务,我可以在运行时检查调整大小,然后task = null,task = new Task.Factory ...您对此有何看法@ HansPassant – Daniel
'if(tokenSource2.Token.IsCancellationRequested)tokenSource2.Cancel();' - 只有当'IsCancellationRequested' **已经是'true'时,才调用'Cancel()',这是没有意义的。你是不是指'if(!tokenSource2.Token.IsCancellationRequested)tokenSource2.Cancel();'? – Noseratio