我有以下任務在列表框的部分項更改時運行。取消創建新的任務時的所有任務
我試圖取消任何正在運行的任務,當用戶更改他們的選擇並開始新的任務時正在運行。我似乎弄清楚爲什麼代碼無法正常工作。
CancellationTokenSource cts;
// The event handeler for when the user makes a selection in the list box
private async void lb1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
clearfileds();
if (cts != null)
{ cts.Cancel(); }
cts = new CancellationTokenSource();
var token = cts.Token;
string sid = lb1.SelectedItem.ToString();
try
{
var series = await LoadSeriesAsync(token, Int32.Parse(sid));
var poster = await LoadPosterAsync(series.PosterBanners[0]);
UpdateSeries(series);
if (File.Exists(poster))
{
ImageSource imageSource = new BitmapImage(new Uri(poster));
imgPoster.Source = imageSource;
}
}
catch (OperationCanceledException)
{MessageBox.Show("we cancell some thing");}
catch (FormatException)
{MessageBox.Show("Please enter a valid series id");}
}
private async Task<TvdbSeries> LoadSeriesAsync(CancellationToken ct, int _seriesId)
{ TvdbSeries seriesloaded = null;
CancellationToken token = ct;
Task<TvdbSeries> SeriesLoadTask = Task.Run(() =>
{
m_tvdbHandler = new TvdbHandler(CacheProvider, "49E28C3EB13EB1CF");
m_tvdbHandler.InitCache();
token.ThrowIfCancellationRequested();
try
{ seriesloaded = m_tvdbHandler.GetSeries(_seriesId, TvdbLanguage.DefaultLanguage, true, true, true, true);
//Just for the test
System.Threading.Thread.Sleep(9000);
}
catch (OperationCanceledException)
{ }
catch (TvdbInvalidApiKeyException ex)
{ MessageBox.Show(ex.Message);}
catch (TvdbNotAvailableException ex)
{ MessageBox.Show(ex.Message);}
return seriesloaded;
});
try
{ seriesloaded = await SeriesLoadTask; }
catch (OperationCanceledException)
{}
return seriesloaded;
}
private async Task<string> LoadPosterAsync(object _param)
{
string posterpath ;
Task<string> PosterLoad = Task.Run(() =>
{
TvdbPosterBanner banner = (TvdbPosterBanner)_param;
banner.LoadBanner();
posterpath = CacheFolder + @"\" + banner.SeriesId + @"\img_posters_" + (banner.BannerPath).Replace(@"posters/", "");
return posterpath;
});
try
{ posterpath = await PosterLoad; }
catch (OperationCanceledException)
{
posterpath = "";
}
return posterpath;
}
所以我試圖讓LoadSeriesAsync取消所有正在運行的其他事件,然後只運行LoadPosterAsync如果LoadSeriesAsync被允許完成的代碼(用戶在加載之前不會改變選擇)。
你能更具體地說「不工作」嗎? – stuartd
對不起,任務不會被取消 – justinf
您需要在LoadSeriesAsync中手動檢查'token.IsCancellationRequested' - 請參閱http://stackoverflow.com/a/3713113/43846 – stuartd