我使用 C# Winforms
我正在使用Task.Run()以使我的 WinForm 不會凍結。
在這段代碼中,我需要更新文本框文本。
我嘗試直接通過 Invoke 更新文本框文本,但沒有成功。
我試圖最小化我的代碼,只關注問題
知道如何更新里面的文本框Task.Run()嗎?
public async void MyFunction()
{
await Task.Run(() =>
{
lvwFiles.BeginInvoke(new Action(() =>
{
foreach (ListViewItem item in this.lvwFiles.Items)
{
txtLog.Text = item.Text "\r\n" txtLog.Text;
if (txtLog.InvokeRequired)
{
txtLog.Invoke(new MethodInvoker(delegate { txtLog.Text = item.Text "\r\n" txtLog.Text; }));
}
Thread.Sleep(4000);
item.BackColor = Color.FromArgb(128, 255, 128);
}
}));
});
}
uj5u.com熱心網友回復:
您正在使用Task.Run在不同的執行緒中運行它,但隨后您正在使用BeginInvoke,它告訴它在 UI 執行緒上運行該代碼。所以結果是您的代碼在 UI 執行緒上運行。并且由于您使用的是Thread.Sleep(),因此您鎖定了 UI 執行緒。
相反,在您的 UI 執行緒上運行它并使用Task.Delay()而不是Thread.Sleep()避免鎖定 UI 執行緒。
public async void MyFunction()
{
foreach (ListViewItem item in this.lvwFiles.Items)
{
txtLog.Text = item.Text "\r\n" txtLog.Text;
await Task.Delay(4000);
item.BackColor = Color.FromArgb(128, 255, 128);
}
}
uj5u.com熱心網友回復:
正如 Gabriel 所指出的,您正在運行一個新執行緒,然后在那個女巫之后立即回傳 UI 執行緒BeginInvoke。您可以使用 Gabriel 的答案,并在 UI 執行緒上運行所有內容,或者您??可以將代碼更改為下面,這樣您將按照BeginInvoke假設將資訊發送到您的 UI 執行緒。
public async void MyFunction()
{
//run your code on new thread
await Task.Run(() =>
{
foreach (ListViewItem item in this.lvwFiles.Items)
{
//whatever has to trigger that UI update is required
if (txtLog.InvokeRequired)
{
//update UI thread
Dispatcher.BeginInvoke(new Action(() => txtLog.Text = item.Text "\r\n" txtLog.Text));
}
// Thread.Sleep(4000); -> I'm not sure if sleep or delay would be required, for me, it looks like a waste of time. And 4 seconds is quite a lot.
//this also looks like UI update, if so, add to dispatcher, or create another one when needed.
item.BackColor = Color.FromArgb(128, 255, 128);
}
});
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/419192.html
標籤:
下一篇:欄位值被推送到錯誤的陣列
