这是我在这个网站上的第一篇文章,所以如果我没有遵守协议,我深表歉意:)
我在 C#.net 中创建了一个表单,并尝试使用 BackgroundWorker 来调用一个类。
我有一个使用 RunWorkerAsync 调用类(名为侦听器)的按钮,但是在调试时我看不到正在调用的类,并且调试器似乎跳过了它。这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
namespace McServer
{
public partial class app : Form
{
BackgroundWorker bgw = new BackgroundWorker();
public app()
{
InitializeComponent();
listener.UpdateLabel += UpdateLabelFromListener;
bgw.WorkerReportsProgress = true;
bgw.WorkerSupportsCancellation = true;
bgw.DoWork += new DoWorkEventHandler(bw_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void startBtn_Click(object sender, EventArgs e)
//private void startBtn_Click(BackgroundWorker bw, EventArgs e)
{
if (bgw.IsBusy != true)
{
// Start the asynchronous operation.
if (ipTxt.Text != "" && portTxt.Text != "" && dirTxt.Text != "")
{
listener t = new listener()
{
ip = ipTxt.Text,
portID = portTxt.Text,
path = dirTxt.Text
};
//bw.DoWork(t);
bgw.RunWorkerAsync(t);
}
else
{
MessageBox.Show("Fill in all fields first");
}
}
}
private void cancelBtn_Click(object sender, EventArgs e)
{
if (bgw.WorkerSupportsCancellation == true)
{
bgw.CancelAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
bgw = sender as BackgroundWorker;
for (int i = 1; i <= 10; i++)
{
if (bgw.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
System.Threading.Thread.Sleep(500);
bgw.ReportProgress(i * 10);
}
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
resultLabel.Text = (e.ProgressPercentage.ToString() + "%");
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
resultLabel.Text = "Canceled!";
}
else if (e.Error != null)
{
resultLabel.Text = "Error: " + e.Error.Message;
}
else
{
resultLabel.Text = "Done!";
}
}
void UpdateLabelFromListener(string message)
{
this.Invoke((Action)(() =>
{
label5.Text = message;
}));
}
private void brwsBtn_Click(object sender, EventArgs e)
{
FolderBrowserDialog dir = new FolderBrowserDialog();
dir.ShowDialog();
dirTxt.Text = dir.SelectedPath;
string path = dirTxt.Text;
}