我有一个由搜索栏过滤的数据视图。我想复制谷歌就像在键盘上搜索一样。
由于数据库可能会变得更大,所以我试图取消以前对下一个字符输入的搜索(它目前相当快,所以我设置了一个睡眠)。
在取消顺序和新的创建之间,似乎每次都不会检查取消令牌。(第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);发布于 2017-04-24 15:24:18
最后我创建了一个List<CancellationTokenSource> cts,然后取消了Last(),然后创建了一个新的。它保持了令牌的活力,并避免了竞赛条件。
https://stackoverflow.com/questions/43516198
复制相似问题