Help with Threading on Winform

I have a Winform with an OK button. The button processes a long query. While the query is running I would like to run a progress bar via a timer to show something happening.
I had to run the long query in another thread so the progress bar would update. When the query ends and the form closes I get a null reference exception. I think it is because of a problem with my threading..  

Enclosed is my code :   Thanks in advance...

                             

            private void btnOK_Click(object sender, System.EventArgs e)
            {
                  this.pictureBox.Visible = true;
                  this.timerProgress.Enabled = true;
                  this.timerProgress.Start();
                  this.progressBar.Visible = true;
                  this.progressBar.Minimum = 0;
                  this.progressBar.Maximum = 25;  //or any other number
                  this.progressBar.Value = 0;
                  this.progressBar.Step = 1;

                  ThreadStart threadStart = new ThreadStart(FilterData);
                  m_WorkerThread = new Thread(threadStart);
                  m_WorkerThread.Start();
                  
            }

                            private void FilterData()
                  {
                // Long queries....................
                                         ThreadFinished (this,new EventArgs());
                              }

                           private void Form1_ThreadFinished(object sender, EventArgs e)
            {
                  this.Close();
            }




LVL 1
JElsterAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ryerrasCommented:
I remember someone asking the question just yesterday, take a look at the thread

http://www.experts-exchange.com/Programming/Programming_Languages/C_Sharp/Q_21194708.html#12509990
0
dsaboCommented:
Hey, it's me again...

Try to kill the thread before  afeter the close statment.

          private void Form1_ThreadFinished(object sender, EventArgs e)
          {
               this.Close();
               try
               {
                     m_WorkerThread.Abort()
               }
               catch{}
          }

you must use try...catch when you abort a thread, because it always throws an exception, as it says the msdn help.

"Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread"

regards, ds
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

JElsterAuthor Commented:
Same error ? Any other ideas? thanks
0
dsaboCommented:
where are you writing this line:

this.ThreadFinished += new EventHandler(Form1_ThreadFinished);


could you paste the exact exception?

regards,
0
JElsterAuthor Commented:
I have that line of code in the OK Click - tried it also in the Load()

The Error is :

      "Object reference not set to an instance of an object."      "Object reference not set to an instance of an object."      string

      _stackTraceString      "   at System.Windows.Forms.UnsafeNativeMethods.IntDestroyWindow(HandleRef hWnd)\r\n   at System.Windows.Forms.UnsafeNativeMethods.DestroyWindow(HandleRef hWnd)\r\n   at System.Windows.Forms.NativeWindow.DestroyHandle()\r\n   at System.Windows.Forms.Control.DestroyHandle()\r\n   at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)\r\n   at CFG.frmMain.ListBar_ItemClick(Object sender, ItemClickEventArgs e) in d:\\capitalfinancialgroup-crm\\main.cs:line 10022\r\n   at Dbi.Controls.dbiListBar.OnPaint(PaintEventArgs e)\r\n   at System.Windows.Forms.Control.PaintWithErrorHandling(PaintEventArgs e, Int16 layer, Boolean disposeEventArgs)\r\n   at System.Windows.Forms.Control.WmPaint(Message& m)\r\n   at System.Windows.Forms.Control.WndProc(Message& m)\r\n   at System.Windows.Forms.ControlNativeWindow.OnMessage(Message& m)\r\n   at System.Windows.Forms.ControlNativeWindow.WndProc(Message& m)\r\n   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)\r\n   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)\r\n   at System.Windows.Forms.ComponentManager.System.Windows.Forms.UnsafeNativeMethods+IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)\r\n   at System.Windows.Forms.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)\r\n   at System.Windows.Forms.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)\r\n   at System.Windows.Forms.Application.Run(Form mainForm)\r\n   at CFG.frmMain.Main() in d:\\capitalfinancialgroup-crm\\main.cs:line 943"      string



THANKS





Thanks
0
dsaboCommented:
What Happens when the form closes? Do you open a new form, or simple shutdown the application?
try inserting a breakpoint over the close statement and check when the application throws an exception, after witch command?
0
JElsterAuthor Commented:
I have a form (Main) that calls this form modal (Search).. then I return back to the Main form.


// Click Event
CFG.Search Filter = new Search();
Filter.Mode      = "Filter";
Filter.LoadMode();
Filter.ShowDialog(this);


The exception is thrown on - m_workerthread.abort()

this.Close();
               try
               {
                     m_WorkerThread.Abort()
               }
               catch{}
0
dsaboCommented:
try using

if(m_WorkerThread.IsAlive)
       m_WorkerThread.Abort();
0
dsaboCommented:
I'm a little bit lost.

Can you paste the complete code.  
Where you call the form, where you create the thread, where you abort the thread, where the windows close, etc
0
JElsterAuthor Commented:
The App starts ... like this:

      static void Main()
            {            
                  try
                  {
                        Application.Run(new frmMain());
                  }
                  catch (Exception err)
                  {
                        MessageBox.Show (err.StackTrace.ToString()+err.Message.ToString()+err.InnerException.ToString(), "Sorry ...CFG-CRM Error",
                              MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                  }
            }



On the Main form is button that calls:


// Click Event
CFG.Search Filter = new Search();
Filter.Mode     = "Filter";
Filter.LoadMode();
Filter.ShowDialog(this);


Filter is the form with the problem - we one we are working on


When the form closes ,   m_WorkerThread.Abort() throws an exception which is caught by the

catch (Exception err)
                  {
                        MessageBox.Show (err.StackTrace.ToString()+err.Message.ToString()+err.InnerException.ToString(), "Sorry ...CFG-CRM Error",
                              MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                  }


In the Main form when it 'returns'...  Thanks!



0
dsaboCommented:
Yes of course.

the Abort() always throws an ThreadAbortException.... ALWAYS...

you should solve this issue by doing nothing when the exception is like ThreadAbortException


try
{
   m_WorkerThread.Abort();
}
catch(ThreadAbortException errAbort)
{
}
catch(Exception err)
{
    MessageBox.Show (err.StackTrace.ToString()+err.Message.ToString()+err.InnerException.ToString(), "Sorry ...CFG-CRM Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}

you could find more information about this on
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemthreadingthreadclassaborttopic.asp 

"Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread while also providing exception information about the thread termination. Calling this method usually terminates the thread."

Hope this helps, DS
0
JElsterAuthor Commented:
Hi.. again... It's null ref. exception not a threadabort...

Right after the ThreadFinished fires and the code returns.. it throws a null ref at the closing '}' on the method.. no matter what I do I can't catch it.  I just don't get it

....
     ThreadFinished (this,new EventArgs());

}   <-- EXCEPTION HERE

            private void Form1_ThreadFinished(object sender, EventArgs e)
            {
            
                  this.Close();      
                  try
                  {
                  //      this.m_WorkerThread.Join();
                  //      m_WorkerThread.Abort();
                  }
                  catch(ThreadAbortException errAbort)
                  {
            
                                    
                  catch(Exception err)
                  {
                        MessageBox.Show (err.StackTrace.ToString()+err.Message.ToString()+err.InnerException.ToString(), "Sorry ...CFG-CRM Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                  }
0
dsaboCommented:
try this, it work's for me once

ThreadFinished (null,new EventArgs());
0
JElsterAuthor Commented:
Doesn't help... I have no idea why this is so difficult.. thanks again...
0
dsaboCommented:
I don't have more ideas....

if you could email some code, so I can try it out.

If you can, send me your email so I can send my..
0
dsaboCommented:
I just heard that we cannot solve the problem using email.

So i try to replicate the problem but had no luck...

here is what I did and it works..

private void button1_Click(object sender, System.EventArgs e)
{
      this.ThreadFinished +=new EventHandler(Form1_ThreadFinished);
      Thread t = new Thread(new ThreadStart(MethodT));
      t.Start();
}

public void MethodT()      
{
      ThreadFinished(this,new EventArgs());
}

private void Form1_ThreadFinished(object sender, EventArgs e)
{
      this.Close();
}
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dsaboCommented:
I forgot this line...

private event EventHandler ThreadFinished;

in the declaration part of the form.....
0
JElsterAuthor Commented:
Hi.. same problem - null ref...

Have you tried calling your form and then returning?  Thanks..
0
JElsterAuthor Commented:
The problem is somewhere in my long process.. if I remark it out.. it works...
0
JElsterAuthor Commented:
I remove the following line of code in my long process the null ref exception goes away at it works..

      dsFilter = DataUtils.Utils.RemoveDupsBasedOnRepId(dsFilter);
            

Why would this cause a null ref? Because it's running in another thread ???????????

Thanks again
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.