[英]ERROR in Threading using Timer and Data
用戶停止在文本框中輸入內容后,我已經實現了流程上的延遲
private System.Timers.Timer timer = new System.Timers.Timer(1000);
public SearchItem(){
timer.AutoReset = false;
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e){
bindingSource.DataSource = logic.GetData(StockCodeTextBox.Text);
}
private void StockCodeTextBox_TextChanged(object sender, EventArgs e){
timer.Stop();
timer.Start();
if (StockCodeTextBox.Text.Equals("")){
AllItemsGridView.ClearSelection();
return;
}
}
用戶停止鍵入后,為什么會出現此錯誤?
System.Windows.Forms.dll中發生類型'System.InvalidOperationException'的異常,但未在用戶代碼中處理
附加信息: 跨線程操作無效:控制'AllItemsGridView'是從不是在其上創建線程的線程訪問的。
UI在WinForms UI Dispatcher線程上更新,而Timer在后台線程上執行。 因此,您不能從不擁有它的線程中更新UI。 一種解決方法是使用此擴展從后台線程更新UI:
public static class ControlExtension
{
public static void Do<TControl>(this TControl control, Action<TControl> action)
where TControl : Control
{
if (control.InvokeRequired)
control.Invoke(action, control);
else
action(control);
}
}
樣品使用:
this.Do(f=>{f.AllItemsGridView.ClearSelection();})
在您的代碼中:
private void StockCodeTextBox_TextChanged(object sender, EventArgs e){
timer.Stop();
timer.Start();
this.Do(f=>{
if (f.StockCodeTextBox.Text.Equals("")){
f.AllItemsGridView.ClearSelection();
}
}
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e){
this.Do(f=>{
f.bindingSource.DataSource = logic.GetData(f.StockCodeTextBox.Text);
}
}
如果您可以自由選擇解決方案,請考慮使用ReactiveUI和.Net 4.5.2重寫您的應用程序。 https://github.com/AdaptiveConsulting/ReactiveTrader
如果使用System.Windows.Forms
,則應使用其隨附的Timer,這樣就不會出現跨線程問題。
代替System.Timers.Timer
使用System.Windows.Forms.Timer
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.