使用BackgroundWorker出现了“调用的目标发生了异常。”

walkingp 2011-01-13 08:47:02
使用了BackgroundWorker组件,在DoWork没有操作界面控件,只在RunWorkerCompleted事件中操作了界面控件,出现了这个错误,如何解决?
        private void bwLoadBlog_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
lblStatus.Text = "已取消";
}
else
{
panel.Visible = false;
int len = listTitle.Count;
dataGridView.RowCount = len;
for (int i = 0; i < len; i++)
{
dataGridView.Rows[i].Cells["Title"].Value = listTitle[i];
}
lblStatus.Text = e.Result.ToString();
}
}


使用委托的方式也出现这种错误,请问如何解决?
        private delegate void AsyncWork(DataTable dt,string str);
private AsyncWork work;
private void UpdatePanel(DataTable dt,string status)
{
int len=dt.Rows.Count;
dataGridView.RowCount = len;
for (int i = 0; i < len; i++)
{
dataGridView.Rows[i].Cells["Title"].Value = listTitle[i];
}
lblStatus.Text = status;
}
private void bwLoadBlog_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else if (e.Cancelled)
{
lblStatus.Text = "已取消";
}
else
{
panel.Visible = false;
int len = listTitle.Count;
DataTable dt = new DataTable();
dt.Columns.Add("Title", Type.GetType("System.String"));
for (int i = 0; i < len; i++)
{
DataRow dr = dt.NewRow();
dr["Title"] = listTitle[i];
dt.Rows.Add(dr);

}

AsyncWork work = new AsyncWork(UpdatePanel);
work(dt, e.Result.ToString());
}
}
...全文
268 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
walkingp 2011-01-13
  • 打赏
  • 举报
回复
嗯嗯,果然是e.Result没有设置。感谢~
zamesking 2011-01-13
  • 打赏
  • 举报
回复
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

你看看e.Result 是不是null, 你在dowork里e.Result 赋值了吗
walkingp 2011-01-13
  • 打赏
  • 举报
回复
我已经找到原因了,我发现只要读取e.Result就会报错,现在把e.Result去掉就不会报这个错误,哪位来解决一下?
zamesking 2011-01-13
  • 打赏
  • 举报
回复
也不知道你这些代码是哪的? 和你上面的代码不太一致。
walkingp 2011-01-13
  • 打赏
  • 举报
回复

//dataGridView.RowCount = len;
for (int i = 0; i < len; i++)
{
// dataGridView.Rows[i].Cells["Title"].Value = listTitle[i];
}
// lblStatus.Text = status;

只要注释掉这三行,就没有异常
zamesking 2011-01-13
  • 打赏
  • 举报
回复
你确信是 backgroundwork 引起的问题? 把 backgroundwoker.runworkansyc注释掉, 问题存在吗?

你的窗体上有哪些控件? 窗体构造函数中 有没有代码会引起异常?
walkingp 2011-01-13
  • 打赏
  • 举报
回复
在DoWork中没有做操作UI的代码
walkingp 2011-01-13
  • 打赏
  • 举报
回复

在 System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
在 System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
在 System.Delegate.DynamicInvokeImpl(Object[] args)
在 System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)
在 System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)
在 System.Threading.ExecutionContext.runTryCode(Object userData)
在 System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
在 System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)
在 System.Windows.Forms.Control.InvokeMarshaledCallbacks()
在 System.Windows.Forms.Control.WndProc(Message& m)
在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
在 System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
在 System.Windows.Forms.Application.Run(Form mainForm)
在 BlogExporter.Program.Main() 位置 E:\\BlogExporter\Program.cs:行号 18
在 System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
在 System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)
在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
在 System.Threading.ThreadHelper.ThreadStart()


刚格式乱了
ggw128 2011-01-13
  • 打赏
  • 举报
回复
估计你应该是在DoWork中做了一些更新UI的动作。比如弹出窗体,或设置某个控件的值。
walkingp 2011-01-13
  • 打赏
  • 举报
回复
" 在 System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)\r\n 在 System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)\r\n 在 System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)\r\n 在 System.Delegate.DynamicInvokeImpl(Object[] args)\r\n 在 System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)\r\n 在 System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)\r\n 在 System.Threading.ExecutionContext.runTryCode(Object userData)\r\n 在 System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)\r\n 在 System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)\r\n 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)\r\n 在 System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)\r\n 在 System.Windows.Forms.Control.InvokeMarshaledCallbacks()\r\n 在 System.Windows.Forms.Control.WndProc(Message& m)\r\n 在 System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)\r\n 在 System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)\r\n 在 System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)\r\n 在 System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)\r\n 在 System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)\r\n 在 System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)\r\n 在 System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)\r\n 在 System.Windows.Forms.Application.Run(Form mainForm)\r\n 在 BlogExporter.Program.Main() 位置 E:\\BlogExporter\\Program.cs:行号 18\r\n 在 System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)\r\n 在 System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)\r\n 在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()\r\n 在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)\r\n 在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)\r\n 在 System.Threading.ThreadHelper.ThreadStart()"
zamesking 2011-01-13
  • 打赏
  • 举报
回复
看看stacktrace。贴出来。
walkingp 2011-01-13
  • 打赏
  • 举报
回复
但这并非是循环内部出错,而是辅助纯种异步操作界面造成的错误。

[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new FormMain());//这里报错
}
wuyq11 2011-01-13
  • 打赏
  • 举报
回复
BackgroundWorker 提供了CancelAsync方法 改变一个属性,并不做任何取消操作
在循环中去判断这个属性,适当时候退出循环

111,119

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧