简体   繁体   中英

Run code in Background Worker

I am trying to work with asp.net. I have very small question. In one of my button click event, I have heavy task that need to be executed and it causing problem. How can i run this code in background worker. Any hint will be appreciated as i have no played with this background worker yet.

Here is the code for my background worker.

  protected void green_button_Click(object sender, EventArgs e)
        {
            string stdOut = null;
            string stdError = null;

            string address = "192.168.1.88";
            string user = "user";


            string pass = "testuser";
            SshExec ssh = new SshExec(address, user, pass);
            green_output.Text = "Connecting...";
            green_output.Text = "Connected";
            ssh.Connect();
            ssh.RunCommand("cfg_green " + green_textbox1.Text + " " + green_textbox2.Text + " " + green_textbox3.Text, ref stdOut, ref stdError);
            green_output.Text = stdOut;
            //green_output.Text = stdError;
            ssh.Close();
            // green_output.Text = "Disconnect";
        } 

In general your question is a little to broad. Not sure if you mean the background worker class which is aviable in WinForms (your tag indicates you mean asp.net 5). Do you really want to use exact this class ?

But i would recommend you to use tasks. See MSDN Task Parallel Library

There you can create and await tasks.

   var result = await Task.Run(() => myBackgroundWork());

Furthermore if your background code supports async (eg network traffic) you could simplay await it and make your code asynchron without using threads.

See for example Doing Work without threads . Threads always come at a cost and you may not want to pay this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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