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:
- User types a single search-string in a textbox.
- I wait 0.5 s then I start to BeginInvoke my delegate pointing to a search method.
- If the user types again a char I want to cancel the Search and begin a new search with the new string typed.
- 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;
}
}
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 ofCancellationToken
(the search thread in your case)Switch to BackGroudWorker , is supports all you need ( NoUI Blocking , Cancellation ect, Progress Reporting..)