【发布时间】:2018-05-04 19:21:17
【问题描述】:
我正在尝试制作一个 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(“这是另一个文本”);不要等待 WritingAnimator("Some text"); ...
我该如何解决?
【问题讨论】:
-
你需要用
await调用它,不要使用async void。 -
所以我下面的代码不好?
-
async与多线程不同。 -
那我该怎么办?
标签: c# multithreading winforms