목록 상자의 섹션 항목이 변경 될 때 실행되는 다음 작업이 있습니다.새 작업이 생성 될 때 모든 작업 취소
사용자가 선택을 변경하고 새 작업을 시작할 때 실행중인 작업을 취소하려고합니다. 코드가 작동하지 않는 이유를 알아낼 수 있습니다.
LoadSeriesAsync을 완료 할 수있는 경우 내가 LoadPosterAsync를 실행하는 다른 모든 이벤트를 취소 에게 LoadSeriesAsync를 얻으려고 노력하고 만 을 실행하고
그래서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;
}
코드 (사용자는로드되기 전에 선택 사항을 변경하지 않습니다.)
"작동하지 않는다"에 대해 더 구체적으로 설명 할 수 있습니까? – stuartd
죄송합니다, 작업이 취소되지 않습니다 – justinf
LoadSeriesAsync에서'token.IsCancellationRequested'를 수동으로 확인해야합니다 - http://stackoverflow.com/a/3713113/43846 – stuartd