取消异步任务如果正在运行。

4

我有一个方法,会在多个场合调用(例如在文本框的 onkeyup 事件中),它会异步地过滤列表框中的项目。

private async void filterCats(string category,bool deselect)
{

    List<Category> tempList = new List<Category>();
    //Wait for categories
    var tokenSource = new CancellationTokenSource();
    var token = tokenSource.Token;

    //HERE,CANCEL TASK IF ALREADY RUNNING


    tempList= await _filterCats(category,token);
    //Show results
    CAT_lb_Cats.DataSource = tempList;
    CAT_lb_Cats.DisplayMember = "strCategory";
    CAT_lb_Cats.ValueMember = "idCategory";

}

和下一个任务相关的内容
private async Task<List<Category>> _filterCats(string category,CancellationToken token)
{
    List<Category> result = await Task.Run(() =>
    {
        return getCatsByStr(category);
    },token);

    return result;
}

我希望测试任务是否已经在运行,如果是,则取消它并使用新值重新启动。我知道如何取消任务,但如何检查它是否已经在运行?


你是否想要在筛选器接收到新值时取消正在运行的任务? - eran otzap
1
你应该研究一下ReactiveExtentions,它有一个TakeLast操作符。 - eran otzap
仔细看了一下@PhilipStuyck的话,使用rx实现可能会更加困难。 我只是认为你不需要那样做。 我想让他接触到Throttle和DistinctUntilChanged,这些是筛选文本框常用的方法。 - eran otzap
1
@david 我已经发布了一个答案,你需要根据自己的需求进行调整。其他人可能会使用RX发布答案,这也可以。但我不会使用我完全不理解的代码。即使是我正在执行的延迟,也可以使用RX完美地实现。学习RX值得你花费一些时间。 - Philip Stuyck
我已经编辑了你的标题。请参考“问题的标题应该包含“标签”吗?”,在那里达成共识是“不应该”。 - John Saunders
显示剩余7条评论
2个回答

6
这是我用来实现这个功能的代码:
if (_tokenSource != null)
{
    _tokenSource.Cancel();
}

_tokenSource = new CancellationTokenSource();

try
{
    await loadPrestatieAsync(_bedrijfid, _projectid, _medewerkerid, _prestatieid, _startDate, _endDate, _tokenSource.Token);
}
catch (OperationCanceledException ex)
{
}

而对于过程调用,它是这样的(当然是简化的):
private async Task loadPrestatieAsync(int bedrijfId, int projectid, int medewerkerid, int prestatieid,
        DateTime? startDate, DateTime? endDate, CancellationToken token)
{
    await Task.Delay(100, token).ConfigureAwait(true);
    try{
        //do stuff

        token.ThrowIfCancellationRequested();

    }
    catch (OperationCanceledException ex)
    {
       throw;
    }
    catch (Exception Ex)
    {
        throw;
    }
}

我进行100毫秒的延迟是因为同一操作会被快速和重复地触发,稍微延迟100毫秒可以让GUI看起来更加响应。


假设 filtercats() 在同一线程上运行。很可能是这样的,他应该注意一下。 - eran otzap

4

看起来你正在寻找一种方法,可以从输入框中输入的文本获取“自动完成列表”,当搜索开始后文本发生更改时,可以取消持续进行的异步搜索。

正如评论中提到的,Rx(响应式扩展)为此提供了非常好的模式,允许您轻松地将UI元素连接到可取消的异步任务中,建立重试逻辑等。

以下小于90行的程序显示了一个“完整的UI”示例(不幸的是不包括任何猫;-)。它包括一些有关搜索状态的报告。

simple UI

我使用 RxAutoComplete 类中的一些静态方法创建了这个示例,以展示如何在小型文档步骤中实现此目标,以及如何组合它们以完成更复杂的任务。

namespace TryOuts
{
    using System;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Reactive.Linq;
    using System.Threading;

    // Simulated async search service, that can fail.
    public class FakeWordSearchService
    {
        private static Random _rnd = new Random();
        private static string[] _allWords = new[] {
            "gideon", "gabby", "joan", "jessica", "bob", "bill", "sam", "johann"
        };

        public async Task<string[]> Search(string searchTerm, CancellationToken cancelToken)
        {
            await Task.Delay(_rnd.Next(600), cancelToken); // simulate async call.
            if ((_rnd.Next() % 5) == 0) // every 5 times, we will cause a search failure
                throw new Exception(string.Format("Search for '{0}' failed on purpose", searchTerm));
            return _allWords.Where(w => w.StartsWith(searchTerm)).ToArray();
        }
    }

    public static class RxAutoComplete
    {
        // Returns an observable that pushes the 'txt' TextBox text when it has changed.
        static IObservable<string> TextChanged(TextBox txt)
        {
            return from evt in Observable.FromEventPattern<EventHandler, EventArgs>(
                h => txt.TextChanged += h,
                h => txt.TextChanged -= h)
                select ((TextBox)evt.Sender).Text.Trim();
        }

        // Throttles the source.
        static IObservable<string> ThrottleInput(IObservable<string> source, int minTextLength, TimeSpan throttle)
        {
            return source
                .Where(t => t.Length >= minTextLength) // Wait until we have at least 'minTextLength' characters
                .Throttle(throttle)      // We don't start when the user is still typing
                .DistinctUntilChanged(); // We only fire, if after throttling the text is different from before.
        }

        // Provides search results and performs asynchronous, 
        // cancellable search with automatic retries on errors
        static IObservable<string[]> PerformSearch(IObservable<string> source, FakeWordSearchService searchService)
        {
            return from term in source // term from throttled input
                   from result in Observable.FromAsync(async token => await searchService.Search(term, token))
                        .Retry(3)          // Perform up to 3 tries on failure
                        .TakeUntil(source) // Cancel pending request if new search request was made.
                   select result;
        }

        // Putting it all together.
        public static void RunUI()
        {
            // Our simple search GUI.
            var inputTextBox = new TextBox() { Width = 300 };
            var searchResultLB = new ListBox { Top = inputTextBox.Height + 10, Width = inputTextBox.Width };
            var searchStatus = new Label { Top = searchResultLB.Height + 30, Width = inputTextBox.Width };
            var mainForm = new Form { Controls = { inputTextBox, searchResultLB, searchStatus }, Width = inputTextBox.Width + 20 }; 

            // Our UI update handlers.
            var syncContext = SynchronizationContext.Current;
            Action<Action> onUITread = (x) => syncContext.Post(_ => x(), null);
            Action<string> onSearchStarted = t => onUITread(() => searchStatus.Text = (string.Format("searching for '{0}'.", t)));
            Action<string[]> onSearchResult = w => { 
                searchResultLB.Items.Clear(); 
                searchResultLB.Items.AddRange(w);
                searchStatus.Text += string.Format(" {0} maches found.", w.Length > 0 ? w.Length.ToString() : "No");
            };

            // Connecting input to search
            var input = ThrottleInput(TextChanged(inputTextBox), 1, TimeSpan.FromSeconds(0.5)).Do(onSearchStarted);
            var result = PerformSearch(input, new FakeWordSearchService());

            // Running it
            using (result.ObserveOn(syncContext).Subscribe(onSearchResult, ex => Console.WriteLine(ex)))
                Application.Run(mainForm);
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接