简体   繁体   中英

WritingAnimation freezes UI

I'm trying to make a WritingAnimator but it freezes the UI when I run it... Here is what I did :

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 :

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"); don't wait for the end of 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"

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) . The whole TPL + async/await features simplify the usage of asynchrony for developers.

Two more thoughts:

  • Maybe you want to provide a CancellationToken in case the user wants to stop the animation.
  • There is also a naming convention regarding methods with async modifiers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM