?
Solved

Help with Threading on Winform

Posted on 2004-11-05
21
Medium Priority
?
529 Views
Last Modified: 2012-05-05
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();
            }




0
Comment
Question by:JElster
21 Comments
 
LVL 6

Expert Comment

by:ryerras
ID: 12511005
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
 
LVL 48

Expert Comment

by:AlexFM
ID: 12511796
0
 
LVL 2

Expert Comment

by:dsabo
ID: 12513257
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:JElster
ID: 12513273
Same error ? Any other ideas? thanks
0
 
LVL 2

Expert Comment

by:dsabo
ID: 12513285
where are you writing this line:

this.ThreadFinished += new EventHandler(Form1_ThreadFinished);


could you paste the exact exception?

regards,
0
 
LVL 1

Author Comment

by:JElster
ID: 12513498
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
 
LVL 2

Expert Comment

by:dsabo
ID: 12513652
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
 
LVL 1

Author Comment

by:JElster
ID: 12513890
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
 
LVL 2

Expert Comment

by:dsabo
ID: 12513917
try using

if(m_WorkerThread.IsAlive)
       m_WorkerThread.Abort();
0
 
LVL 2

Expert Comment

by:dsabo
ID: 12513931
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
 
LVL 1

Author Comment

by:JElster
ID: 12513992
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
 
LVL 2

Expert Comment

by:dsabo
ID: 12514036
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
 
LVL 1

Author Comment

by:JElster
ID: 12514596
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
 
LVL 2

Expert Comment

by:dsabo
ID: 12514862
try this, it work's for me once

ThreadFinished (null,new EventArgs());
0
 
LVL 1

Author Comment

by:JElster
ID: 12514904
Doesn't help... I have no idea why this is so difficult.. thanks again...
0
 
LVL 2

Expert Comment

by:dsabo
ID: 12514948
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
 
LVL 2

Accepted Solution

by:
dsabo earned 1280 total points
ID: 12515172
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
 
LVL 2

Expert Comment

by:dsabo
ID: 12515176
I forgot this line...

private event EventHandler ThreadFinished;

in the declaration part of the form.....
0
 
LVL 1

Author Comment

by:JElster
ID: 12517018
Hi.. same problem - null ref...

Have you tried calling your form and then returning?  Thanks..
0
 
LVL 1

Author Comment

by:JElster
ID: 12517073
The problem is somewhere in my long process.. if I remark it out.. it works...
0
 
LVL 1

Author Comment

by:JElster
ID: 12517321
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

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
Screencast - Getting to Know the Pipeline
Suggested Courses
Course of the Month16 days, 6 hours left to enroll

850 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question