I am very new to thread. However I would like to make 2 threads, Thread A and Thread B. When a button is clicked Thread A starts and so does Thread B. Thread B shows a loading image and disables users from clicking any buttons whilst Thread A executes some logic code. Thread B continues to run untill the logic in thread A is executed and thus Thready A is stopped.

Is it better to use a single or two thread in this case? How can I do this?

By default there's already a thread that handles the program's GUI (window), which in your case could be the Thread B - so you can directly use this one.

To run a method inside a thread you could use something like this:

Thread threadA = new Thread(new ThreadStart(someMethod));  //'someMethod' runs in threadA 
threadA.Start();

Then you can use Invoke() inside Thread A to update the program's interface (because you can only do this from the UI thread, otherwise you get an exception):

Invoke((MethodInvoker) otherMethod); //'otherMethod' is called from the UI thread, use it to disable buttons, showing images, etc.

can you please explain further how the invoke works?

Invoke is used to execute a method in the UI thread even if everything else runs on the worker thread. It takes as an argument a delegate to the method you want to call (what I wrote up there is a short version). When Invoke is called from the worker thread, a message is sent to the UI thread, that tells it to execute that delegate which you supplied as an argument.

Basically, it works as a "portal" between the worker thread and the UI thread.

I will say, while the main thread for the form is there, I personally don't care to use it because it locks up the form, and you can't move it or alt+tab in and out easily, ext.

Also if you are still puzzled about Invoke look at it this way.

Threads are seperate from each other, you could almost think of them as their own individual program each. So when you create a variable in one program, you can't simply try and call it in another program. So if you remember, by default, you have 1 thread already that is tied to the form, and code you are creating (and includes added items like buttons, text boxes, ext).

Now if another thread wants to access that item, that was created on the form's thread (we mentioned above), you have to ask the first thread for access to this item, since it owns it.

(Also, don't quote me on this, but I believe Invoke can help prevent Threads clashing, which can be catastrophic, usually crashing the program, because Threads can run simultaneously, they can try and access the same item at the same time, which is not good).

Well at least this is how I understand it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.