這只是示例(用WPF編寫)如何實現此目的。你可以很容易地將它用於winforms。
var form = new Window();
var tb = new TextBox();
form.Content = tb;
form.Show();
var str = "alk;lfkdsfj;slfhjs;idjhf;lksdjf;klsdjf;'lkjds;lfksd";
Task.Run(() =>
{
foreach (var c in str.ToCharArray())
{
Thread.Sleep(100);
form.Dispatcher.Invoke(() =>
{
tb.Text += c;
});
}
});
UPD。 對於Windows窗體,它可能是一個棘手和更復雜的異步/等待答案。但是,不管怎樣,我可以顯示如何做到這一點沒有異步東西
void Main()
{
var form = new MyForm();
form.Show();
}
class MyForm : Form
{
private TextBox tb;
public MyForm()
{
tb = new TextBox();
tb.Width = 300;
this.Controls.Add(tb);
var btn = new Button();
btn.Text = "go";
btn.Width = 300;
btn.Location = new System.Drawing.Point(0, 50);
this.Controls.Add(btn);
btn.Click += (sender, args) =>
{
tb.Text = string.Empty;
var str = "alk;lfkdsfj;slfhjs;idjhf;lksdjf;klsdjf;'lkjds;lfksd";
SetText d = SetTextToTb;
Task.Run(() =>
{
foreach (var c in str.ToCharArray())
{
Thread.Sleep(100);
tb.Invoke(d, c);
}
});
};
}
public delegate void SetText(char text);
void SetTextToTb(char text)
{
tb.Text += text;
}
}
'Thread.Sleep'阻塞了UI線程,所以無法更新。嘗試等待'Task.Delay'而不是讓你的代碼異步/等待。 – juharr
嘗試使用:backgroundworker –