开发者

How can I cancel an asynchronous delegate in C# 3.5?

开发者 https://www.devze.com 2023-01-28 16:35 出处:网络
I have searched google up and down but I can not find nearly any proper information about that topic.

I have searched google up and down but I can not find nearly any proper information about that topic.

What I wanna do is this:

  1. User types a single search-string in a textbox.
  2. I wait 0.5 s then I start to BeginInvoke my delegate pointing to a search method.
  3. If the user types again a char I want to cancel the Search and begin a new search with the new string typed.
  4. The UI-Thread must not be blocked!

How can I do that using C# 3.5 ?

UPDATE:

View:

private void OnTextChanged(...)
{
   if (SearchFormatEvent != null)
   {
       ICollection<object> 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<object> SearchInputTextStrategy<T>(string param);

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

        public SearchProvider(ITextView view)
        {
            _view = view;
            _view.SearchFormat开发者_如何学运维Event += 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;                
        }
    }


Switch to BackGroudWorker , is supports all you need ( NoUI Blocking , Cancellation ect, Progress Reporting..)


Have a look at CancellationTokenSource and CancellationToken, it is a thread safe method to signal cancellation.

You use the CancellationTokenSource to signal Cancellation to all owners of CancellationToken (the search thread in your case)

0

精彩评论

暂无评论...
验证码 换一张
取 消