如何解决跨线程操作无效异常? [英] how to solve cross thread operation not valid Exception?
本文介绍了如何解决跨线程操作无效异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在项目中使用backgroundworker控件显示进度条,并且在backgroundWorker_Dowok事件中遇到跨线程异常.
请帮忙.
这是我的代码:
I''m using backgroundworker control in my project, to show the progress bar, and I am getting cross thread exception in backgroundWorker_Dowok event.
Please help.
Here is my code:
private void btnGenerate_Click(object sender, EventArgs e)
{
toolStripProgressBar1.Style = ProgressBarStyle.Marquee;
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
bool flag;
try
{
clientid = convert.ToString(ddlClientName.SelectedValue);
clientid = Convert.ToString(ddlprincipalname.SelectedValue);
clid = Convert.ToInt32(ddlClientName.SelectedValue);
prid = Convert.ToInt32(ddlprincipalname.SelectedValue);
flag = check_op_close_stock();
if (flag)
{
excel_header();
get_excel_data();
get_nostk_transit();
set_formating();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
推荐答案
您必须利用InvokeRequired
属性和Control
类的Invoke()
方法.
检查此 [
You have to make use ofInvokeRequired
property and theInvoke()
method of aControl
class.
Check this[^] article for the details/examples.
那里有大量的文章.请查阅msdn的官方文档:
http://msdn.microsoft.com/en-us/library/ms171728(VS .80).aspx [ ^ ]
您没有发布更新进度条的方法,但是必须在此方法中检查所需的调用.
它应该看起来像这样:
There are tons of articles out there. Check out the official msdn documentation:
http://msdn.microsoft.com/en-us/library/ms171728(VS.80).aspx[^]
You did not post the method that updates the progress bar, but the invoke required must be checked in this method.
It should look something like this:
private void setProgress(int nValue)
{
if(progressBar.InvokeRequired)
progressBar.Invoke(new my_delegate(setProgress),new object[]{nValue});
else
{
progressBar.Value = nValue;
}
}
private delegate void my_delegate(int nValue);
这篇关于如何解决跨线程操作无效异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文