[英]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.