【发布时间】:2017-01-10 19:27:44
【问题描述】:
我需要一些有关 BackgroundWorker 的帮助。使用 Visual Studio 2015 及其 windows 窗体
我是这种东西的新手,真的不知道它是如何工作的等等。我到目前为止的代码是基于这里的各种帖子。
worker_DoWork_ 根本没有被解雇,但不知道为什么。我相信这与 DataRceivedEventHandler 有关,因为当我移动 If 我移动 worker.DoWork += worker_DoWork_;和 worker.RunWorkerAsync();进入按钮单击事件并禁用 DataReceivedEventHandler,方法 worker_DoWork_ 被触发,我可以使用 DoSomeWork 下分配的任何静态文本更新 textBox。
另外,我不知道如何通过 DoSomeWork 将大纲数据传递到文本框中。
有人可以帮忙吗。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
namespace CMD_testing
{
public partial class Form1 : Form
{
BackgroundWorker worker;
private delegate void DELEGATE();
public Form1()
{
InitializeComponent();
worker = new BackgroundWorker();
}
private void button2_Click(object sender, EventArgs e)
{
Process process;
process = new Process();
process.StartInfo.FileName = @"C:\\Project\Test\Data.bat";
process.StartInfo.UseShellExecute = false;
// process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
process.StartInfo.RedirectStandardInput = true;
process.Start();
process.BeginOutputReadLine();
// process.WaitForExit();
// process.Close();
}
private void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (outLine.Data != null)
{
Console.WriteLine("Im here...");
worker.DoWork += worker_DoWork_;
//worker.RunWorkerAsync();
Console.WriteLine("Im here NOW");
Console.WriteLine(outLine.Data); //its outputed fine into the console
}
}
private void worker_DoWork_(object sender, DoWorkEventArgs e)
{
Console.WriteLine("I'm at worker_DoWork_");
Delegate del = new DELEGATE(DoSomeWork);
this.Invoke(del);
}
private void DoSomeWork()
{
Thread.Sleep(1000);
textBox1.Text = "????"; // how to pass outline.Data in here
}
}
}
【问题讨论】:
-
为什么评论了 //worker.RunWorkerAsync();???
-
因为我收到异常错误提示 Backgroundworker 已经在运行并且无法同时运行。因此,我相信 DataReceivedHandler 是其中之一,但我可能错了
-
您需要取消注释该行。如果您尝试第二次运行它,那么它将崩溃。所以首先,检查 if (!worker.IsBusy) { worker.RunWorkerAsync(); } - 只有在当前未运行时才允许它运行。
-
很酷。然而。我的文本框仅在 CMD 完成运行后更新。我需要实时更新它。此外,似乎该方法只调用一次,而不是每次从 CMD 接收数据时调用。
标签: c# multithreading backgroundworker