Hi, I'm new to C# programming,that's why I have a lot to learn.I'm trying to understand how to create and work with threads in C#.Here's the code of my demo project.Please if somebody can see this code and help me to understand why I get an error when I start the code.The app stops after a while and show me an error that I don't understand and don't know how to fix it. Please if somebody can help me I'll be very happy and thankful.
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Threading;
The problem is in your StartThread method. Since it runs on a different thread, you're not allowed to access the Form's controls. You need to use Invoke to perform the changes you want to do on the original thread.
When the button is clicked to stop the thread, then the while loop in StartThread() exits, and the thread terminates.
It looks like you're using bStartThread to control the non-UI thread, with the intention that it continues running. If so, you should enclose the code in StartThread in an infinite loop:
while( true ) { while( this.bStartThread ) { Thread.Sleep(500); // invoke a delegate on the form to update dataSet. } }
and only Start the thread if its IsAlive property is false.
Otherwise, if your intention is to allow the thread to stop when clicking the button, then you've got more work to do:
You should Join() the thread after setting bStartThread to false, otherwise the user could click the button (if they're a fast clicker!) to start the thread again before it had finished terminating and you'd be attempting to Start a thread that is still in the started state.
You can't Start a terminated thread, so you'd have to go ahead and create a new thread instance each time.
private void StartThread() { while ( this.bStartThread ) { Thread.Sleep(500); Console.WriteLine("About to invoke"); // BeginInvoke - don't want to block waiting for UI thread to update, // as it's going to be busy waiting for this work to be completed. this.BeginInvoke( new AddRowDelegate( AddRow ) ); Console.WriteLine("invoked"); } }
Microsoft is conducting an online survey to understand your opinion of the Msdn Web site. If you choose to participate, the online survey will be presented to you when you leave the Msdn Web site.