none
BackGroundWorker与UI线程同步【求助】 RRS feed

  • 问题

  • 功能,使用Backgroudworker实现与UI线程的同步问题,其中worker通知UI作更新,然后等待UI线程唤醒worker线程。

    代码描述:在一个form里面添加一个button,用于激活worker,一个label用于显示worker里面的更新的值。

    运行时出错 {"Exception has been thrown by the target of an invocation."}

     

    查了相关的backgroundworker的用法,基本上都是这么用的,也不清楚问题出在哪里,求大牛们指点,谢谢

     

     

    代码具体如下

    --------------------------------------------------------------------------------

        public partial class testEditor : Form

        {

            private AutoResetEvent locker = new AutoResetEvent(false);

     

            private int process = 0;

     

            public testEditor()

            {

                InitializeComponent();

            }

     

            private void btn_testThread_Click(object sender, EventArgs e) {

                worker.RunWorkerAsync();

            }

     

            private void worker_DoWork(object sender, DoWorkEventArgs e) {

                BackgroundWorker worker = sender as BackgroundWorker;

                Thread.Sleep(1000);

                worker.ReportProgress(process++);

                Console.WriteLine("DoWork, before lock ");

                locker.WaitOne();

                Console.WriteLine("DoWork, after lock ");

            }

     

            private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) {

                BackgroundWorker worker = sender as BackgroundWorker;

                Console.WriteLine("UI thread, before update ui info ");

                label2.Text = "Number = " + e.UserState.ToString();

                Console.WriteLine("UI thread, after update ui, release lock");

                locker.Set();

            }

     

            private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {

                Console.WriteLine("worker completed ");

            }

        }

    异常的详细描述如下:

    System.Reflection.TargetInvocationException was unhandled

      Message=Exception has been thrown by the target of an invocation.

      Source=mscorlib

      StackTrace:

           at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)

           at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)

           at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)

           at System.Delegate.DynamicInvokeImpl(Object[] args)

           at System.Windows.Forms.Control.InvokeMarshaledCallbackDo(ThreadMethodEntry tme)

           at System.Windows.Forms.Control.InvokeMarshaledCallbackHelper(Object obj)

           at System.Threading.ExecutionContext.runTryCode(Object userData)

           at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)

           at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)

           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

           at System.Windows.Forms.Control.InvokeMarshaledCallback(ThreadMethodEntry tme)

           at System.Windows.Forms.Control.InvokeMarshaledCallbacks()

           at System.Windows.Forms.Control.WndProc(Message& m)

           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)

           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)

           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)

           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)

           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)

           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)

           at System.Windows.Forms.Application.Run(Form mainForm)

           at WebMaster.Program.Main() in C:\ZhangHui\work\WebMaster\WebMaster\Program.cs:line 19

           at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)

           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)

           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()

           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)

           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

           at System.Threading.ThreadHelper.ThreadStart()

      InnerException: System.NullReferenceException

           Message=Object reference not set to an instance of an object.

           Source=WebMaster

           StackTrace:

                at WebMaster.editor.testEditor.worker_ProgressChanged(Object sender, ProgressChangedEventArgs e) in C:\ZhangHui\work\WebMaster\WebMaster\editor\testEditor.cs:line 47

                at System.ComponentModel.BackgroundWorker.OnProgressChanged(ProgressChangedEventArgs e)

                at System.ComponentModel.BackgroundWorker.ProgressReporter(Object arg)

           InnerException: 

    2011年6月19日 3:14

答案

  • InnerException: System.NullReferenceException

    Message=Object reference not set to an instance of an object.

     

    这个才是重点。。。尝试调试一下,看是在哪里抛出来的?


    学习学习....
    • 已标记为答案 cylixhui 2011年6月21日 3:14
    2011年6月20日 3:34

全部回复

  • InnerException: System.NullReferenceException

    Message=Object reference not set to an instance of an object.

     

    这个才是重点。。。尝试调试一下,看是在哪里抛出来的?


    学习学习....
    • 已标记为答案 cylixhui 2011年6月21日 3:14
    2011年6月20日 3:34
  • 好的,谢谢,本人新手,我仔细调试一下
    2011年6月21日 3:13