Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;                
        }
    }
like image 343
Pascal Avatar asked Nov 30 '10 12:11

Pascal


2 Answers

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

like image 76
TalentTuner Avatar answered Nov 14 '22 00:11

TalentTuner


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)

like image 32
thumbmunkeys Avatar answered Nov 13 '22 23:11

thumbmunkeys