简体   繁体   English

在后台工作程序中运行代码

[英]Run code in Background Worker

I am trying to work with asp.net. 我正在尝试使用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). 不知道您的意思是WinForms中可用的后台工作者类(您的标记表示您的意思是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 请参阅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. 此外,如果您的后台代码支持异步(例如,网络流量),则可以在不使用线程的情况下使simplay等待它,并使代码异步。

See for example Doing Work without threads . 例如,参见“没有线程进行工作” Threads always come at a cost and you may not want to pay this. 线程总是要付出代价的,您可能不想为此付出代价。

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

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