簡體   English   中英

WritingAnimation凍結UI

[英]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 / asyncC#語言功能,Task.DelayTask Parallel Library(TPL)的一部分 整個TPL +異步/等待功能簡化了開發人員對異步的使用。

還有兩個想法:

  • 也許您想提供一個CancellationToken ,以防用戶想要停止動畫。
  • 關於帶有異步修飾符的方法,還有一個命名約定

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM