[英]C# thread-safe calls on dynamically created controls
我知道如何在用戶控件上執行線程安全的調用,但是當它們動態生成時,我沒有任何線索。 我試圖列出它們的數組列表(富文本框),然后我遇到了“參數啟動線程”委托的問題。 您的輸入非常感謝。
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.currentBox.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke( d, new object[] { text } );
}
else
{
this.currentBox.Text += text;
}
}
// This method is executed on the worker thread and makes
// a thread-safe call on the TextBox control. On a specific text box.....
private void ThreadProcSafe()
{
int i = 0;
while(_stop_threads == false) {
this.SetText(String.Format("{0}\n", i));
++i;
Thread.Sleep(100);
}
this.SetText(String.Format("Thread Time: {0}:{1}:{2}\n", DateTime.Now.TimeOfDay.Hours, DateTime.Now.TimeOfDay.Minutes, DateTime.Now.TimeOfDay.Seconds));
}
問題是,盡管每個UI控件都有單獨的線程,但是Windows窗體只能在單個線程下工作。 因此,從單獨的線程更新UI控件是不安全的。
也許您可以從這些線程中填充字典或數組,並在Form的單線程下更新該數組中的結果。 這樣,您將從更新后的值數組中同時更新所有UI控件,這是線程安全的,並且消耗更少的系統資源。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.