我已經搜索谷歌上下,但我幾乎找不到任何有關該主題的正確信息。如何取消C#3.5中的異步委託?
我想做的事是這樣的:
- 用戶類型單一的搜索字符串文本框。
- 我等了0.5秒,然後我開始BeginInvoke指向搜索方法的委託。
- 如果用戶再次鍵入一個字符,我想取消搜索並開始一個新的搜索,並輸入新的字符串。
- 不能阻止UI線程!
我該如何使用C#3.5?
UPDATE:
查看:
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;
}
}
你是如何產卵後臺搜索方法? – Lazarus 2010-11-30 12:30:32
我更新了一個代碼示例!往上看! – Pascal 2010-11-30 12:50:50
您不能以乾淨的方式停止執行非協作功能。你需要一個這個功能定期檢查的標誌。 `CancellationToken`在.net 4中執行此操作,不知道3.5中是否有內置類。 – CodesInChaos 2010-11-30 13:05:37