简体   繁体   English

停止长时间运行的事件

[英]Stop long running events

I have a following form Form3 that is opened by another form Form1, and when closed Form1 opens back up.我有一个由另一个表单 Form1 打开的以下表单 Form3,当关闭 Form1 时,它会重新打开。

The problem is when I close Form3 DoSomething keeps running after form is closed.问题是当我关闭 Form3 时,DoSomething 在表单关闭后继续运行。

I understand that I can make DoSomething into a thread and set IsBackground = true but is there another way to stop all processes when form closes.我知道我可以将 DoSomething 变成一个线程并设置 IsBackground = true 但还有另一种方法可以在表单关闭时停止所有进程。

This code is just example, For illustration.此代码只是示例,用于说明。

   public partial class Form3 : Form
    {

    public Form3()
    {
        InitializeComponent();
    }
    private void DoSomething()
    {
        int i = 0;
        while(true)
        {
            if (!this.IsDisposed)
            {
                Application.DoEvents();
                i++;
                Thread.Sleep(10);
                label1.Text = i.ToString();
                dataGridView1.Rows.Add();
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DoSomething();
    }

    private void Form3_FormClosed(object sender, FormClosedEventArgs e)
    {
        this.Dispose();
        Form1.Default.Show();
    }

}

You never break out of the while(true).你永远不会突破 while(true)。 You should either break the loop when it's IsDisposed is true, change your while loop to while(!IsDisposed), or store use a class level variable that determines when to break the loop.您应该在 IsDisposed 为 true 时中断循环,将 while 循环更改为 while(!IsDisposed),或者存储使用确定何时中断循环的类级别变量。

I would probably opt for the latter, as it gives you a little more control.我可能会选择后者,因为它给了你更多的控制权。

public partial class Form3 : Form
{
    volatile bool clDoSomething;

    public Form3()
    {
        InitializeComponent();
    }
    private void DoSomething()
    {
        int i = 0;
        clDoSomething = true;
        while(clDoSomething)
        {
            Application.DoEvents();
            ++i;
            Thread.Sleep(10);
            label1.Text = i.ToString();
            dataGridView1.Rows.Add();
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DoSomething();
    }

    private void Form3_FormClosed(object sender, FormClosedEventArgs e)
    {
        clDoSomething = false;
        Form1.Default.Show();
    }

}

Your fundamental approach is flawed.你的基本方法有缺陷。

First off, Application.DoEvents should be avoided unless you are sure that you really need it, and that you are using it correctly.首先,应避免使用Application.DoEvents,除非您确定确实需要它并且正确使用它。 You do not need it here, and you are not using it correctly.您在这里不需要它,并且您没有正确使用它。

What you really need here is a Timer .你真正需要的是一个Timer

private Timer timer = new Timer();
private int count = 0;
public Form3()
{
    InitializeComponent();

    timer.Tick += timer_Tick;
    timer.Interval = 10;

    //when the form is closed stop the timer.
    FormClosed += (_, args) => timer.Stop();
}

private void button1_Click(object sender, EventArgs e)
{
    count = 0;
    timer.Start();
}

private void timer_Tick(object sender, EventArgs e)
{
    count++;
    label1.Text = count.ToString();
    dataGridView1.Rows.Add();
}

When the Form is create the Timer is configured.创建Form时,配置Timer The tick event is set, along with the interval.滴答事件与间隔一起设置。 The tick event will look similar to your DoSomething method;滴答事件看起来类似于你的DoSomething方法; it will involve running some bit of code every 10 seconds, from the UI thread, while keeping the UI responsive.它将涉及每 10 秒从 UI 线程运行一些代码,同时保持 UI 响应。 When the form is closed simply stop the timer and it will stop firing off these events.当表单关闭时,只需停止计时器,它将停止触发这些事件。

Also note that in this example here pressing the button multiple times simply resets the timer and the count, it doesn't end up creating two loops that each fire every 10 milliseconds.另请注意,在此示例中,多次按下按钮只会重置计时器和计数,它最终不会创建两个循环,每个循环每 10 毫秒触发一次。

根据需要覆盖this.Dispose()this.Close()并手动this.Close() DoSomething() 。

Thanks to cdhowie suggestions and input of all others.感谢 cdhowie 的建议和所有其他人的投入。 Mowing DoEvents to the end and adding IsDipsosed solved my problem.将 DoEvents 修剪到最后并添加 IsDipsosed 解决了我的问题。

public partial class Form3 : Form
{
    public Form3()
    {
        InitializeComponent();
    }
    private void DoSomething()
    {
        int i = 0;
        while ((true) && !this.IsDisposed)
        {
                i++;
                Thread.Sleep(10);
                label1.Text = i.ToString();
                dataGridView1.Rows.Add();
                Application.DoEvents();
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {
        DoSomething();
    }

    private void Form3_FormClosed(object sender, FormClosedEventArgs e)
    {
        Form1.Default.Show();
    }

}

try to add this intsruction in the FormClosing event : System.Diagnostics.Process.GetCurrentProcess().Kill();尝试在 FormClosing 事件中添加此指令: System.Diagnostics.Process.GetCurrentProcess().Kill();

it's a little bit like this:有点像这样:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    System.Diagnostics.Process.GetCurrentProcess().Kill();
}

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

相关问题 在长时间运行的方法上停止任务 - Stop Task on long running method 安全地停止长时间运行的任务 - Safely stop long running task 如何为长时间运行的作业停止Windows服务? - How to Stop a Windows Service for long running Jobs? 如何使用按钮停止长时间运行的循环 - How to stop long running loop using button C#类设计 - 事件和长时间运行的方法 - C# Class Design - Events & long running methods 有什么优雅的方法可以取消/停止长时间运行的线程? - Is there any elegant way to cancel/stop a long running thread? 开始,停止,暂停和继续运行很长时间的方法 - Start, Stop, Pause and Continue a very long running method 如何使用JavaScript停止ASP.NET上正在进行的回发(长时间执行)? - How to stop ongoing postback (long running execution) on asp.net using javascript? Windows Service Application仅执行一次长时间运行的任务,并在完成后自行停止 - Windows Service Application to perform long-running task only once and stop itself after completion 如何停止BackgroundWorker的DoWork处理程序仅包含一个(长时间运行)语句? - How to stop BackgroundWorker whose `DoWork` handler only contains one (long-running) statement?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM