How can I cancel an asynchronous delegate in C# 3.

2019-06-17 02:20发布

问题:

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.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;                
        }
    }

回答1:

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



回答2:

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)