當用戶調整窗口大小時應該更新一些長文本,但是如果線程已經運行,應該停止並使用新的寬度參數重新開始。取消線程並重新啓動它
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