开发者

How to run the application continously without hanging in background

I have a problem in running the application continuously without hanging (Appending Data).

I want to run this code without hanging in background for every 5 seconds.

My code is:

    public void Button1_Cli开发者_如何转开发ck(System.Object sender, System.EventArgs e)
    {
        if (Button1.Text == "Start")
        {
            Timer1.Interval = 5000;
            Timer1.Enabled = true;
            Button1.Text = "Stop";
        }
        else if (Button1.Text == "Stop")
        {
            Timer1.Enabled = false;
            Button1.Text = "Start";
        }
    }


Or, you can implement it as Windows service, which will run in background of your system without showing explicitly. In the main thread you can perform required actions with 5 second delays.


You'd have to use BackgroundWorker.

Put the process that causes UI hanging, (Timer1_Tick in your code) in DoWork(object sender, DoWorkEventArgs e) method and invoke it by calling RunWorkerAsync.
There's a nice tutorial at http://www.dotnetperls.com/backgroundworker

Remember not to use any thread-specific variable in the DoWork method. You have to pass them as paramaters to the method.

UPDATE: Here's what your code should look like:
Not Tested

public void Timer1_Tick(System.Object sender, System.EventArgs e)
  {
  var bgw = new BackGroundWorker();
  bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
  }  

void bgw_DoWork(object sender, DoWorkEventArgs e)
  {
  // Put you try-catch block here.
  }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜