如何将函数传递给过载backgroundWorker1.RunWorkerAsync(?) [英] How to pass function into overload backgroundWorker1.RunWorkerAsync(?)

查看:112
本文介绍了如何将函数传递给过载backgroundWorker1.RunWorkerAsync(?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

环境:Visual Studio 2010(C#),SQL Server 2012,DB2

项目类型:Windows窗格



问题描述:

我有一个耗时的从SQL Server db获取数据的过程:



private void getAllPartsByDrawingNo(string sValue),没有返回值

或者它可能是:

private int getAllPartsByDrawingNoFunc(string sValue)返回1.



我会喜欢使用BackgroundWorker和ProgressBar来显示进度(参见下面的代码)。



问题:我明白我必须在RunWorkerAsync(???)重载中以某种方式调用上面的函数但我无法弄清楚如何做到这一点,或者我可能完全错了吗?如果可能的话给我一个很好的例子



代码:

private void btnStart2_Click(object sender,EventArgs e)

{

btnStart2.Enabled = false;

btnCancel2.Enabled = true;



backgroundWorker1.RunWorkerAsync( ???);

}



private void backgroundWorker1_DoWork(object sender,DoWorkEventArgs e)

{

for(int i = 0; i< 100; i ++)

{

Thread.Sleep(100);



if(i%5 == 0)

{

backgroundWorker1.ReportProgress(i);

}



if(backgroundWorker1.CancellationPending)

{

e.Cancel = true;

backgroundWorker1.ReportProgress(0);

返回;

}

}

backgroundWorker1.ReportProgress(100) ;

}

...到目前为止..

Environment: Visual Studio 2010 (C#), SQL Server 2012, DB2
Type of Project: Windows Forms

Problem description:
I have a time-consuming process for getting data from SQL Server db:

private void getAllPartsByDrawingNo(string sValue) with no returning value
or it could be:
private int getAllPartsByDrawingNoFunc(string sValue) which return 1.

I would like to use BackgroundWorker and ProgressBar to show the progress (see code below).

Question: I understand that I have to call above function somehow in RunWorkerAsync(???) overload but I cannot figure out how to do that, or maybe I completely wrong in that? If possible show me a good example

Code:
private void btnStart2_Click(object sender, EventArgs e)
{
btnStart2.Enabled = false;
btnCancel2.Enabled = true;

backgroundWorker1.RunWorkerAsync(???);
}

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i < 100; i++)
{
Thread.Sleep(100);

if (i % 5 == 0)
{
backgroundWorker1.ReportProgress(i);
}

if(backgroundWorker1.CancellationPending)
{
e.Cancel = true;
backgroundWorker1.ReportProgress(0);
return;
}
}
backgroundWorker1.ReportProgress(100);
}
…and so far..

推荐答案

否 - 查看MSDN文档,它包括一个例子le。



您可以在BackgroundWorker.DoWork事件处理程序中调用实际函数,并通过sender参数(即工作程序实例)报告进度。

您的主线程然后处理ProgressChanged事件并向用户显示更新的值。
No - have a look at the MSDN documentation, it includes an example.

You call the actual function in the BackgroundWorker.DoWork event handler, and report progress there, via the sender parameter which is the worker instance.
Your main thread then handles the ProgressChanged event and displays the updated value to the user.


这篇关于如何将函数传递给过载backgroundWorker1.RunWorkerAsync(?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆