【问题标题】:How can I cancel an asynchronous delegate in C# 3.5?如何在 C# 3.5 中取消异步委托?
【发布时间】:2010-11-30 12:26:08
【问题描述】:

我在 google 上上下搜索过,但几乎找不到关于该主题的任何适当信息。

我想做的是:

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

如何使用 C# 3.5 做到这一点?

更新

查看

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

搜索提供者

// This is the delegate invoked for the async search taking the searchstring typed by the user
    public delegate ICollection<object> SearchInputTextStrategy<T>(string param);

    public class SearchProvider : ISearchProvider
    {
        private ITextView _view;
        private SearchInputTextStrategy<object> searchInputDelegate;

        public SearchProvider(ITextView view)
        {
            _view = view;
            _view.SearchFormatEvent += new ConstructSearchFormatDelegate(CostructSearchFormat);
        } 

        private string SearchFormat(string param)
        { 
            // compute string

            return string.Empty; //...
        }

        public ICollection<object> CostructSearchFormat(string param)
        {
            var searchfilter = SearchFormat(param);

             IAsyncResult pendingOperation = searchInputDelegate.BeginInvoke("searchfilter",null,null);

            // How can I cancel the Async delegate ?

            ICollection<object> result = searchInputDelegate.EndInvoke(pendingOperation);

            return result;                
        }
    }

【问题讨论】:

  • 你是如何产生后台搜索方法的?
  • 我更新了一个代码示例!见上文!
  • 你不能以干净的方式停止非合作函数的执行。您需要一个该函数定期检查的标志。 CancellationToken 在 .net 4 中执行此操作,不知道 3.5 中是否有内置类。

标签: c# asynchronous delegates


【解决方案1】:

切换到 BackGroudWorker ,支持您所需要的一切(NoUI Blocking,Cancellation ect,Progress Reporting..)

【讨论】:

  • @Pascal - 你能分享你的完整解决方案的源代码吗?
【解决方案2】:

看看CancellationTokenSourceCancellationToken,这是一种线程安全的方法来表示取消。

您使用CancellationTokenSourceCancellationToken 的所有所有者(您的案例中的搜索线程)发出取消信号

【讨论】:

    猜你喜欢
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-23
    • 2015-12-05
    • 1970-01-01
    • 2012-06-08
    • 2010-11-27
    相关资源
    最近更新 更多