【问题标题】:WritingAnimation freezes UIWritingAnimation 冻结 UI
【发布时间】: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


【解决方案1】:
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 的方法: 使用其他线程”

await / asyncC# 语言功能,因为版本 5 和 Task.Delay任务并行库 (TPL) 的一部分的方法.整个 TPL + async/await 功能简化了开发人员对异步的使用。

还有两个想法:

  • 也许您想提供CancellationToken 以防用户想要停止动画。
  • 还有一个 naming convention 与带有异步修饰符的方法有关。

【讨论】:

  • 感谢您的回答。所以我尝试了它,但结果与我在第二个代码中所做的结果相同。
  • 正如一个评论已经建议的那样,问题是您没有使用 await 调用 WritingAnimator - 这是不需要的行为的根本原因 - 如果您的代码仍然无法正常工作,还有另一个问题超出您的代码 sn-p 的范围
猜你喜欢
  • 2022-01-25
  • 2015-01-16
  • 2019-09-16
  • 2015-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-30
相关资源
最近更新 更多