简体   繁体   English

如何从form1打开form2(从异步任务)

[英]How to open form2 from form1 (from async task)

I'm trying to open form2 from an async task in form1. 我正在尝试从form1中的异步任务打开form2。 When I try to open it using: 当我尝试使用以下方式打开它时:

public void DoWorkPollingTask()
{
    Form f2 = new Form2();
    Task.Run(async () =>
            {
                while (true)
                {
                    f2.Show();

                    await Task.Delay(10000);
                }
            });
}

it shows me this: 它告诉我这个: 在此输入图像描述

Please don't be confused about that Internet Connection Error. 请不要对此Internet连接错误感到困惑。 It's not an actual popup from visual studio, it's just my form2, but the problem is, it's not completely loaded as you can see on that image. 它不是来自visual studio的实际弹出窗口,它只是我的form2,但问题是,它没有完全加载,因为你可以在该图像上看到。 It should look like this: 它应该如下所示: 在此输入图像描述

Is there any way I can show form2 from a task timer task that runs every x seconds? 有没有什么办法可以从每x秒运行一次的任务计时器任务中显示form2?

You're trying to access UI elements from the non-UI thread, and that's imply going to cause lots of problems. 您正在尝试从非UI线程访问UI元素,这意味着会导致很多问题。

Simply don't use a thread pool thread, as there's no reason to do so here at all. 只是不要使用线程池线程,因为这里没有理由这样做。

public async void DoWorkPollingTask()
{
    Form f2 = new Form2();
    while (true)
    {
        f2.Show();

        await Task.Delay(10000);
    }
}

Is there any way I can show form2 from a task timer task that runs every x seconds? 有没有什么办法可以从每x秒运行一次的任务计时器任务中显示form2?

You could use an actual timer, if you prefer. 如果您愿意,可以使用实际计时器。 The code is already very simple, but if you simply prefer using a timer, then use a timer. 代码已经非常简单,但如果您只是喜欢使用计时器,那么请使用计时器。 Just make sure you use a timer designed to work with a UI framework, rather than one of the system timers, so that it'll fire the event in the UI thread. 只需确保使用设计用于UI框架的计时器,而不是系统计时器之一,以便它将在UI线程中触发事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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