yo245
yo245

Reputation: 1

Why do I sometimes get System.NullReferenceException in Winforms app?

It happens rarely and has happened to me only in debugging mode, but it drives me crazy. this is the function it happens in: (in the code behind of form)

        public override bool Func()
        {
            if (this.InvokeRequired)
            {
                return (bool)this.Invoke((Func<bool>)delegate
                {
                    return this.SomeRadioButton.Checked;  // Happens in this line
                });
            }
            else
            {
                return this.SomeRadioButton.Checked;
            }
        }

and this is the exception: (I just edited the names and paths for privacy reasons)

System.NullReferenceException: Object reference not set to an instance of an object.
   at Project.Forms.Layouts.SomeForm.Func() in C:\Users\.........cs:line 2824
   at Project.Forms.MainForm.backgroundWorkerDoWorkFunc() in C:\Users\.......cs:line 5091  
   at System.ComponentModel.BackgroundWorker.OnDoWork(DoWorkEventArgs e)
   at System.ComponentModel.BackgroundWorker.WorkerThreadStart(Object argument)
   at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs)
   at System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink)
   at System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.DoAsyncCall()
   at System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(Object o)
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

I don't know why this bug happens, it happens rarely.

Thanks very much.

I don't know why you closed my questions, it's not the same as What is a NullReferenceException, and how do I fix it? because there is no answer for this scenario there

Upvotes: -1

Views: 112

Answers (1)

user5638373
user5638373

Reputation:

Make sure that bg worker starts AFTER components initialization. I susoct that she to order of your drag an drop bg worker is before init tgan rest of form. This way first work happen before some radio button is created.

Upvotes: 0

Related Questions