[英]WritingAnimation freezes UI
我正在嘗試制作一個WritingAnimator,但是當我運行它時它會凍結UI。這就是我所做的:
public partial class Tsia : Form
{
[...]
private void TypeText()
{
WritingAnimator("Some text");
WritingAnimator("This is another text");
}
private void WritingAnimator(string text)
{
foreach (char c in text)
{
TextBox1.AppendText(c.ToString());
Thread.Sleep(100);
}
}
}
因此,我在Google上進行了搜索,發現了一種避免使用其他線程凍結UI的方法:
public partial class Tsia : Form
{
[...]
private void TypeText()
{
WritingAnimator("Some text");
WritingAnimator("This is another text");
}
private async void WritingAnimator(string text)
{
foreach (char c in text)
{
TextBox1.AppendText(c.ToString());
await Task.Delay(100);
}
}
}
但是由於WritingAnimator(“ This is another text”),它的輸入類似於“ Some text”和“ This is another text”的混合體。 不要等待WritingAnimator(“ Some text”);的結尾; ...
我該如何解決?
public partial class Tsia : Form
{
[...]
private async Task TypeText()
{
await WritingAnimator("Some text");
await WritingAnimator("This is another text");
}
private async Task WritingAnimator(string text)
{
foreach (char c in text)
{
TextBox1.AppendText(c.ToString());
await Task.Delay(100);
}
}
}
“所以我在Google上進行搜索,發現了一種避免使用其他線程凍結UI的方法”
從版本5開始, await
/ async
是C#語言功能,而Task.Delay
是Task Parallel Library(TPL)的一部分 。 整個TPL +異步/等待功能簡化了開發人員對異步的使用。
還有兩個想法:
CancellationToken
,以防用戶想要停止動畫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.