[英]Thread cancellation token for direct search bar
我有一個由搜索欄過濾的datagridview。 我想重現類似keyup的google。
由於數據庫可能會變大,因此我試圖取消對下一個字符輸入的先前搜索(當前速度非常快,因此我進行了睡眠)。
似乎在取消順序和新創建之間並非每次都檢查canceltoken。 (第2行和第5行)看起來很正常,但為此感到煩惱。
所述令牌是否有“在設置新線程之前向所有線程顯示”的方法? 還是調用舊令牌的方法? 也許清單? 將字典設置為日期時間?
對此系統的任何建議都將受到歡迎。
private CancellationTokenSource cts { get; set; }
protected async void SearchGrid(object Sender, EventArgs e)
{
FullGridView.CurrentCell = null;
cts = cts ?? new CancellationTokenSource
();
cts.Cancel();
List<string> SearchFor = Box.Text.Split(null).ToList();
cts = new CancellationTokenSource();await Task.Run(() =>
{
try
{
foreach (DataGridViewRow Row in FullGridView.Rows)
{ if ((Row.Cells[0].Value as bool?) == true)
{ continue; }
cts.Token.ThrowIfCancellationRequested();
bool Found = false;
Found = SearchFor.All(s =>
ColumnIndexToSearch.Any(c =>
Row.Cells[c].Value != null &&
Row.Cells[c].Value.ToString().ToUpperInvariant()
.Contains(s.ToUpperInvariant())));
SyncCtx.Post(delegate
{
Row.Visible = Found;
}, null);
Thread.Sleep(5000); //Test purpose
}
}
catch
{
return;
}
}, cts.Token);
最后,我創建了一個List<CancellationTokenSource> cts
然后取消了Last()
然后創建了一個新的。 它保持令牌有效並避免競爭狀況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.