为了执行长时间运行的操作(在这个上下文中让它是搜索),我将加载逻辑放在TPL任务中,因此在后台线程上调用通用方法 search ()。Search()操作可能足够长,所以我需要使用CancellationToken正确取消它的能力。但是Search()操作直到完成才返回,所以我必须做一些逻辑来实现方便和(!)快速的取消。
使用的WaitHandle的我可以实现这样的东西:
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 {}
}
}
在我看来,这似乎不是那么优雅的解决方案。
Q:这个任务还有其他的方法吗?
如果您控制了StartSearchInternal()
和Search(eHandle)
,那么您应该能够在Search
核心环路中与ThrowIfCancellationRequested
进行协作取消。
要了解更多细节,我强烈建议阅读这个文档:"在。net Framework 4中使用取消支持"。
顺便说一句,您可能应该在ViewModel类的某个地方存储对Task.Factory.StartNew(() => StartSearchInternal(s.Token), s.Token)
返回的任务的引用。您很可能想要观察它的结果和它可能抛出的任何异常。你可能想看看Lucian Wischik的"异步重入,以及处理它的模式"。
这是我的评论重构成一个包含代码的回答。它包含了几个使用Task的备选方案。Wait和async模式,选择哪个取决于你是否从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();
}
}
}