BackgroundWorker 的问题,帮忙看看是什么回事,谢谢
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
this.label1.Text = e.UserState.ToString();
this.label1.Update();
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("运算终于完成了");
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
work(this.backgroundWorker1);
}
private bool work(BackgroundWorker bk)
{
int tatle = 10000;
for (int i = 0; i < tatle; i++)
{
if (bk.CancellationPending) //这里判断一下是否用户要求取消后台进行,并可以尽早退出。
{
bk.ReportProgress(i, String.Format("当前值是 {0},操作被用户申请中断", i));
return false;
}
//处理的过程中,通过这个函数,向主线程报告处理进度,最好是折算成百分比,与外边的进度条的最大值必须要对应。这里,我没有折算,而是把界面线程的进度条最大值调整为与这里的总数一致。
bk.ReportProgress(i, String.Format("当前值是 {0} ", i));
}
return true;
}
private void button2_Click(object sender, EventArgs e)
{
this.backgroundWorker1.CancelAsync();
}
private void button1_Click(object sender, EventArgs e)
{
//这一句,就是让后台工作开始。
this.backgroundWorker1.RunWorkerAsync();
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
上面是一个简单测试BackGroundWorker的例子,但是按BUTTON1运行的时候,就提示错误:{"调用的目标发生了异常。"}。我调试了一下,发现是 Application.Run(new Form1());这里提示的错误
请问这个是什么原因。之前没有搞过这类的程序,麻烦帮忙看看,谢谢
------解决方案--------------------
你把断点吓到DoWork处调试吧