Run code in Background Worker

笑着哭i 提交于 2019-12-04 05:06:46

问题


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

回答1:


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 (e.g. 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.



来源:https://stackoverflow.com/questions/31042185/run-code-in-background-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!