简体   繁体   English

C#Windows窗体应用程序:加载窗体后,如何在后台执行某些操作?

[英]C# Windows Form Application : how to do something in background after the form has been loaded?

In my Windows Form Application, I successfully run the form: 在Windows窗体应用程序中,我成功运行了该窗体:

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. ...表格即将关闭/崩溃。

I tried to specify a special event handler in the Load property of the form but it didn't help: 我试图在表单的Load属性中指定一个特殊的事件处理程序,但没有帮助:

This piece of code works (I have a string "Hello" written and the form is alive): 这段代码有效(我写了一个字符串“ Hello”,并且该表单仍然有效):

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? 我的问题是如何组织代码,以便在加载表单后可以在后台执行某些操作?

If you wanted to do something like this you could use the BackgroundWorker . 如果您想做这样的事情,可以使用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类变量,并且需要在构造函数中放置一些代码:

private BackgroundWorker _worker = new BackgroundWorker();

::ctor
{
    _worker.DoWork += DoBackgroundWork;

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

then you need to define the DoWork handler: 那么您需要定义DoWork处理程序:

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);
    }
}

and notice I'm checked the CancellationPending property to ensure we exit gracefully if necessary. 并注意我已经检查了CancellationPending属性,以确保必要时我们可以正常退出。 Later on, if you need to (eg when you close the form), call this: 稍后,如果需要(例如,当您关闭表单时),请调用此命令:

_worker.CancelAsync();

to shut it down. 关闭它。

Finally, to start it up, call this: 最后,要启动它,请调用此命令:

_worker.RunWorkerAsync();

Look at BackgroundWorker component it was specifically designed to allow you to do work in the background and report progress/change to the UI. 查看BackgroundWorker组件,它是专门设计用来允许您在后台进行工作并向UI报告进度/更改的组件。

Note that you're also pausing the UI thread by calling Thread.Sleep(1000) which probably won't end well. 请注意,您还通过调用Thread.Sleep(1000)暂停了UI线程,这可能不会很好地结束。

You can find documentation on background workers here - http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx 您可以在此处找到有关后台工作人员的文档-http://msdn.microsoft.com/zh-cn/library/system.componentmodel.backgroundworker.aspx

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

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