How to implement Multi Threading in .NET
Hi all.
I wonder if there is someone that can help me?
I am a fairly new developer. I have been developing for about two years now and only over the past 2 months with C# in depth. I have come across a situation which requires that I implement multithreading in my application. So far, so good and easy. I have done a lot of research about it but nothing that I have come across actaully helps me with what I want and need to do. Let me explain.
I am writing an application which is used to import data from an excel spread sheet into a datagridview on the form. Once all the data is in the grid, the user will then specify the database connection and basically hit "GO". The idea is that on go, the program iterates through every record on the data grid and imports it in the database.
Now, that part is all wonderfull and it works beautifully in terms of functionality. However, the datagrid will at some times have up to 4500 rows. Thus making it a "long running function" while it commits the data. The issue is that I need to find a way to show a progress bar. I created a new form, added a Progress bar to it and set its Style to Marquee. Then All I do is declare a new instance of the form, show the form as a dialog, Commit the data, and then close the instance of the ProgressForm. Sounds simple.
However, The problem with this was that I couldn't "paint" my UI while the "Main thread" was sending the data to the DB. So I researched multi threading. Came across some good examples, but was still stuck with an issue. Basically I need the "worker thread" to be able to access the information which is in the "UI Thread". The data which is being commited, needs to come from the datagridview. But it can't be done. I get an error which says, control accessed from a different thread to the one on which is was created. Not only did I get the error, the general consensus across the internet is that it is bad coding practice.
I don't know how else I can get this right and if there is anyone who can help me, I would appreciate it. Also, should you require any further information about the work that I am trying to do, Please let me know....
Thanks in advance.
Ricardo Carvalho