如何在C#3.5中取消异步委托?

我上下搜索谷歌,但我找不到关于该主题的任何适当信息。

我想做的是:

  1. 用户在文本框中键入单个搜索字符串。
  2. 我等了0.5秒然后我开始BeginInvoke我的委托指向搜索方法。
  3. 如果用户再次键入char,我想取消搜索并开始新的搜索,并输入新的字符串。
  4. 不得阻止UI-Thread!

我怎么能用C#3.5做到这一点?

更新

查看

private void OnTextChanged(...) { if (SearchFormatEvent != null) { ICollection collection = SearchFormatEvent("MySearchString"); // Do stuff on the returned collection } } 

SearchProvider

 // This is the delegate invoked for the async search taking the searchstring typed by the user public delegate ICollection SearchInputTextStrategy(string param); public class SearchProvider : ISearchProvider { private ITextView _view; private SearchInputTextStrategy searchInputDelegate; public SearchProvider(ITextView view) { _view = view; _view.SearchFormatEvent += new ConstructSearchFormatDelegate(CostructSearchFormat); } private string SearchFormat(string param) { // compute string return string.Empty; //... } public ICollection CostructSearchFormat(string param) { var searchfilter = SearchFormat(param); IAsyncResult pendingOperation = searchInputDelegate.BeginInvoke("searchfilter",null,null); // How can I cancel the Async delegate ? ICollection result = searchInputDelegate.EndInvoke(pendingOperation); return result; } } 

切换到BackGroudWorker,支持您所需的一切(NoUI阻止,取消等,进度报告..)

看看CancellationTokenSource和CancellationToken ,它是一种线程安全的信号取消方法。

您使用CancellationTokenSource向CancellationToken的所有所有者(在您的情况下为搜索线程)发出取消信号