C# Windows 窗体应用程序:加载窗体后如何在后台执行某些操作? [英] C# Windows Form Application : how to do something in background after the form has been loaded?

查看:44
本文介绍了C# Windows 窗体应用程序:加载窗体后如何在后台执行某些操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 Windows 窗体应用程序中,我成功运行了窗体:

In my Windows Form Application, I successfully run the form:

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());

它有效.我已经加载了表单.

It works. I have the form loaded.

但是如果我在加载表单后在一个循环中执行某些操作,例如...

But if I do something in a cycle after the form has been loaded, say ...

String MyLog = Directory.GetCurrentDirectory() + "\\MyLog.txt";

while (true)
{
                using (StreamWriter writer = new StreamWriter(MyLog, true))
                {
                    writer.Write("Hello");
                }
                Thread.Sleep(1000);
}

...表单正在关闭/崩溃.

... the form is getting closed/crashed.

我试图在表单的 Load 属性中指定一个特殊的事件处理程序,但没有帮助:

I tried to specify a special event handler in the Load property of the form but it didn't help:

这段代码有效(我写了一个字符串Hello"并且表单是活动的):

This piece of code works (I have a string "Hello" written and the form is alive):

private void formLoad(object sender, EventArgs e)
    {
          String MyLog = Directory.GetCurrentDirectory() + "\\MyLog.txt";


                    using (StreamWriter writer = new StreamWriter(MyLog, true))
                    {
                        writer.Write("Hello");
                    }
                    Thread.Sleep(1000);

    }

这段代码不起作用(我加了一个循环)——表单崩溃了:

This piece of code doesn't work (I added a cycle) - the form is crashed:

   private void formLoad(object sender, EventArgs e)
    {
          String MyLog = Directory.GetCurrentDirectory() + "\\MyLog.txt";

          while (true)
          {
                    using (StreamWriter writer = new StreamWriter(MyLog, true))
                    {
                        writer.Write("Hello");
                    }
                    Thread.Sleep(1000);
          }

    }

我的问题是如何组织代码以便在加载表单后可以在后台执行某些操作?

My question is how can I organize a code so that I can do something in the background after the form is loaded?

推荐答案

如果你想做这样的事情,你可以使用 BackgroundWorker.但是有些事情你需要知道.首先,要设置它,您需要一个 private 类变量,并且需要在构造函数中放入一些代码:

If you wanted to do something like this you could use the BackgroundWorker. But there are some things you need to know. Firstly, to set it up, you need a private class variable and you need to put some code in the constructor:

private BackgroundWorker _worker = new BackgroundWorker();

::ctor
{
    _worker.DoWork += DoBackgroundWork;

    // we set this so you can cancel softly if necessary
    _worker.WorkerSupportsCancellation = true;
}

然后你需要定义DoWork处理程序:

then you need to define the DoWork handler:

private void DoBackgroundWork(object sender, DoWorkEventArgs e)
{
    String MyLog = Directory.GetCurrentDirectory() + "\\MyLog.txt";

    while (!_worker.CancellationPending)
    {
        using (StreamWriter writer = new StreamWriter(MyLog, true))
        {
            writer.Write("Hello");
        }
        Thread.Sleep(1000);
    }
}

并注意我检查了 CancellationPending 属性以确保我们在必要时正常退出.稍后,如果您需要(例如,当您关闭表单时),请调用:

and notice I'm checked the CancellationPending property to ensure we exit gracefully if necessary. Later on, if you need to (e.g. when you close the form), call this:

_worker.CancelAsync();

关闭它.

最后,要启动它,请调用:

Finally, to start it up, call this:

_worker.RunWorkerAsync();

这篇关于C# Windows 窗体应用程序:加载窗体后如何在后台执行某些操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆