具有取消能力的长期运行模式

时间:2014-05-08 10:39:35

标签: c# wpf task-parallel-library cancellation long-running-processes

为了执行长时间运行(让它在此上下文中搜索)操作,我将加载逻辑放在TPL任务中,因此在后台线程上调用通用方法 Search()搜索()操作可能足够长,因此我需要能够使用 CancellationToken 正确取消它。但 Search()操作直到完成才返回,所以我必须做一些逻辑才能实现方便和(!)快速取消。

使用 WaitHandle's 我可以实现以下内容:

private void StartSearch() // UI thread
{
    CancellationTokenSource s = new CancellationTokenSource();
    Task.Factory.StartNew(() => StartSearchInternal(s.Token), s.Token)
}

private void StartSearchInternal(CancellationToken token) // Main Background Thread
{
    ManualResetEvent eHandle = new ManualResetEvent(false);
    Task.Factory.StartNew(() => Search(eHandle ), TaskScheduler.Default);
    WaitHandle.WaitAny(new [] { eHandle, token.WaitHandle });
    token.ThrowIfCancellationRequested();
}

private IEnumerable<object> Search(ManualResetEvent e) // Another Background thread
{
    try
    {
        // Real search call, i.e. to database, service, or AD, doesn't matter
        return RealSearch();
    }
    catch {} // Here, for simplicity of question, catch and eat all exceptions
    finally
    {
        try
        {
            e.Set();
        }
        catch {} 
    }
}

在我看来,这不是那么优雅的解决方案,可以制作。

问:此任务还有其他方法吗?

2 个答案:

答案 0 :(得分:2)

如果您可以控制StartSearchInternal()Search(eHandle),那么您应该能够在ThrowIfCancellationRequested核心循环内与Search合作取消。

有关详细信息,我强烈建议您阅读此文档:"Using Cancellation Support in .NET Framework 4"

另外,您应该在ViewModel类的某个地方存储Task.Factory.StartNew(() => StartSearchInternal(s.Token), s.Token)返回的任务的引用。你很可能想要观察它的结果以及它可能抛出的任何异常。您可能想查看Lucian Wischik的"Async re-entrancy, and the patterns to deal with it"

答案 1 :(得分:1)

这是我的评论重构为包含代码的答案。它包含几个使用Task.Wait和异步模式的替代方案,其选择取决于您是否从UI线程调用该方法。

对O / P和其他答案有几条评论,其中包含有关异步行为的有价值信息。请阅读以下代码,因为下面的代码有许多“改进机会”。

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace SearchAgent
{
    class CancellableSearchAgent
    {
        // Note: using 'object' is a bit icky - it would be better to define an interface or base class,
        // or at least restrict the type of object in some way, such as by making CancellableSearchAgent
        // a template CancellableSearchAgent<T> and replacing every copy of the text 'object' in this
        // answer with the character 'T', then make sure that the RealSearch() method return a collection
        // of objects of type T.
        private Task<IEnumerable<object>> _searchTask;
        private CancellationTokenSource _tokenSource;

        // You can use this property to check how the search is going.
        public TaskStatus SearchState
        {
            get { return _searchTask.Status; }
        }

        // When the search has run to completion, this will contain the result,
        // otherwise it will be null.
        public IEnumerable<object> SearchResult { get; private set; }

        // Create a new CancellableSearchAgent for each search.  The class encapsulates the 'workflow'
        // preventing issues with null members, re-using completed tasks, etc, etc.
        // You can add parameters, such as SQL statements as necessary.
        public CancellableSearchAgent()
        {
            _tokenSource = new CancellationTokenSource();
            _searchTask = Task<IEnumerable<object>>.Factory.StartNew(() => RealSearch(), TaskScheduler.Default);
        }

        // This method can be called from the UI without blocking.
        // Use this if the CancellableSearchAgent is part of your ViewModel (Presenter/Controller).
        public async void AwaitResultAsync()
        {
            SearchResult = await _searchTask;
        }

        // This method can be called from the ViewModel (Presenter/Controller), but will block the UI thread
        // if called directly from the View, making the UI unresponsive and unavailable for the user to
        // cancel the search.
        // Use this if CancellableSearchAgent is part of your Model.
        public IEnumerable<object> AwaitResult()
        {
            if (null == SearchResult)
            {
                try
                {
                    _searchTask.Wait(_tokenSource.Token);
                    SearchResult = _searchTask.Result;
                }
                catch (OperationCanceledException) { }
                catch (AggregateException)
                {
                    // You may want to handle other exceptions, thrown by the RealSearch() method here.
                    // You'll find them in the InnerException property.
                    throw;
                }
            }
            return SearchResult;
        }

        // This method can be called to cancel an ongoing search.
        public void CancelSearch()
        {
            _tokenSource.Cancel();
        }
    }
}