Implementing a cancel button in my app

H

holysmokes99

I am trying to implement a cancel button on my application that ingests
a bunch of data from a text file into a database. I have not worked too
much with threads, so I am having some trouble. I had this working fine
for VB.Net using .Net framework 1.0, but when I upgraded to Visual
Studio 2005, I get an error saying that what I am doing is not thread
safe. The error makes sense to me, but I am just confused on how to fix
it.

In a nutshell, I have a form where the user inputs a bunch of
variables, including the text file where the app can find the data that
should be ingested. On this form are various status indicators that are
constantly updating during the data ingest, like a progress bar, a
couple of labels indicating how many rows have been ingested, etc. When
the user clicks the "Ingest Data" button, the app creates another
thread that goes off on it's merry way and does the ingest. When a user
clicks cancel, the thread is killed (eventually). So the GUI is the
main thread, and the data ingest sub is the spawned thread. The way I
had it coded in VS 2002, the spawned thread referenced the controls on
the GUI (the main thread), and it also updated the status indicator
controls on the GUI. Now, the error I get in VS2005 when I try to
access or write to the properties of the controls on the GUI is
"Cross-thread operation not valid: Control '[CONTROL NAME HERE]'
accessed from a thread other than the thread it was created on." This
error occurs all the way down for the form controls that my spawned
thread is accessing. Not only do I need to read from the controls on
the GUI in this thread, I need to write to them as well to update the
status of the data ingesting.

As I mentioned above, I am new to threads and don't really know the
best way to tackle this. As far as reading from the controls on the
GUI, I can write these values to some globablly visible variables and
then read them from within the thread. However, this seems very sloppy.
But even that will not help me write back to the GUI for my status
indicators.

Thanks for any suggestions.

Marcus
 
T

Truong Hong Thi

The error message is right. VS2005 work harder than its ancestors to
detect and prevent such errors. You should only update the control on
the thread that created it. Control class provides you with 2 method
to do this: Control.Invoke and Control.BeginInvoke. I think there are
many samples on the Web about this.

Thi
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top