【问题标题】:How to start and pause the background running thread from another form buttons?如何从另一个表单按钮启动和暂停后台运行线程?
【发布时间】:2013-06-17 15:24:09
【问题描述】:

我有两种形式。 form1 调用在加载期间启动后台运行线程。 一旦它开始运行。 form 2 将弹出有两个按钮(开始和停止)。 当我按下停止按钮时,线程应该暂停,当我按下开始时,暂停线程应该从它停止的地方开始执行。

我尝试使用此代码。

   myResetEvent.WaitOne();//  to pause  the thread

   myResetEvent.Set();   // to resume the thread.

因为这些事件是在 form1 中定义的,但我希望它在 form2 中起作用。

【问题讨论】:

  • 欢迎来到Stack Overflow,您需要将后台工作人员传递给其他表单并尝试取消,例如:abortableBackgroundWorker1.CancelAsync();
  • @JeremyThompson 谢谢...你能帮我解决上述问题吗..
  • 通过代码转换器将其转换为 C#:stackoverflow.com/questions/13206926/… 然后将代码更改为不隐藏lblClose_LinkClicked 方法中的表单。然后只需重命名 lblClose.Text = "Restart" 并再次启用计时器。 HTH
  • 你把这搞混了。 WaitOne(0) 调用需要在工作代码中。表单类应该只调用 Set() 或 Reset()。

标签: c# windows winforms


【解决方案1】:

终于我得到了答案,它适用于我的情况,发布它,可能会对其他人有所帮助..

Form 1 代码..

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace thread_example
{
public partial class Form1 : Form
{
    private int i = 0;
    public Thread Run_thread = null, run1 = null; // thread definition
    public static AutoResetEvent myResetEvent = new AutoResetEvent(false);//intially set to false..
    public Form1()
    {
        InitializeComponent();
        run1 = new Thread(new ThreadStart(run_tab));
        run1.IsBackground = true;
        run1.Start();
    }

    private void run_tab()
    {
        //do something.        

    }

    private void button1_Click(object sender, EventArgs e)
    {
        form2 f2 = new form2();
        f2.Show();
    }
}
}




// Form 2 code...

  namespace thread_example
  {
    public partial class form2 : Form
  {
    public form2()
    {
        InitializeComponent();
    }

    private void btn_stop_Click(object sender, EventArgs e)
    {
        Form1.myResetEvent.WaitOne();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Form1.myResetEvent.Set();
    }
 }
}

【讨论】:

    【解决方案2】:

    您可以将 Event 实例作为表单参数传递给第二个表单。

    class Form1
    {
      ManualEvent myResetEvent;
    
      void ShowForm2()
      {
        var form2 = new Form2(myResetEvent);
        form.ShowDialog();
      }
    }
    
    class Form2
    {
      ManualEvent myResetEvent;
    
      Form2(ManualEvent event)
      {
        myResetEvent = event;
      }
    
      void StopButtonClick()
      {
        myResetEvent.Reset();
      }
    
      void ContinueButtonClick()
      {
        myResetEvent.Set();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-23
      • 2023-03-29
      • 1970-01-01
      • 2018-04-17
      • 2023-03-20
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      • 2020-02-02
      相关资源
      最近更新 更多