本文介绍了在代码 c# 中插入延迟/等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    public void OpenUpForm(object sender, EventArgs e)
    {
        if (forms.Count == numberoftimes)
        {
            forms.ForEach(f =>
            {
                f.Close();
                f.Dispose();
            });
            forms.Clear();
            //Need Delay Here
            return;
        }
        forms.Add(new Form1());
        forms.Last().Show();
    }

您好,我有这段代码,我需要在 forms.Clear(); 之后添加延迟但我是编码新手,我无法弄清楚.我尝试过 Task.DelayThread.Sleep 但它锁定了我的用户界面.是否可以添加延迟锁定应用程序?谢谢.

Hello I have this code, I need to add delay after forms.Clear(); But im new to coding i couldnt figure it out.I have tryed with Task.Delay and Thread.Sleep but it locks my user interface. Is it possible to add a delay that dosent lock the application? Thank you.

推荐答案

您可以将方法标记为异步并使用:

You can mark the method async and use this:

await Task.Delay(2000);

不会阻塞ui线程

public async void OpenUpForm(object sender, EventArgs e)
{
    if (forms.Count == numberoftimes)
    {
        forms.ForEach(f =>
        {
            f.Close();
            f.Dispose();
        });
        forms.Clear();
        await Task.Delay(2000);
        return;
    }
    forms.Add(new Form1());
    forms.Last().Show();
}

这会像这样.

  • 创建一个新任务,该任务在 2 秒后运行完成
  • Ui 线程被冒泡以继续执行/处理其他事件
  • 2 秒结束后,UI 线程返回并从 await 之后继续执行异步方法

这篇关于在代码 c# 中插入延迟/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 19:02
查看更多