[英]WritingAnimation freezes UI
I'm trying to make a WritingAnimator but it freezes the UI when I run it... Here is what I did : 我正在尝试制作一个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);
}
}
}
So I searched on Google and I found a way to avoid freezing the UI by using other threads : 因此,我在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);
}
}
}
But it types something like a mix of "Some text" and "This is another text" beacause WritingAnimator("This is another text"); 但是由于WritingAnimator(“ This is another text”),它的输入类似于“ Some text”和“ This is another text”的混合体。 don't wait for the end of WritingAnimator("Some text");
不要等待WritingAnimator(“ Some text”);的结尾; ...
...
How could I fix it ? 我该如何解决?
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);
}
}
}
"So I searched on Google and I found a way to avoid freezing the UI by using other threads"
“所以我在Google上进行搜索,发现了一种避免使用其他线程冻结UI的方法”
await
/ async
is a C# language feature since version 5 and Task.Delay
is a method which is part of the Task Parallel Library (TPL) . 从版本5开始,
await
/ async
是C#语言功能,而Task.Delay
是Task Parallel Library(TPL)的一部分 。 The whole TPL + async/await features simplify the usage of asynchrony for developers. 整个TPL +异步/等待功能简化了开发人员对异步的使用。
Two more thoughts: 还有两个想法:
CancellationToken
in case the user wants to stop the animation. CancellationToken
,以防用户想要停止动画。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.