When and why should we use threads?

Asked

Viewed 1,710 times

1

When and why should we use threads? I’d like a few examples.

  • 6

    You have a few questions that may help: http://answall.com/q/123173/101, http://answall.com/q/131108/101, http://answall.com/q/1946/101, http://answall.com/q/14904/101 and http://answall.com/q/95233/101 One of them should, or the whole answer that.

3 answers

4


Keep in mind that every program already has at least one thread, which is the thread main (where it is running). There are a thousand and one reasons to use thread, and each programmer should know the best occasion, but I could list some:

  1. Long-term duties: sometimes we have to invoke some function that takes some time to execute. If you do not create a new thread, this function will be executed in the main thread, or thread main, and it will seem that your program has stopped responding;
  2. Non-priority tasks: it is possible to define the priority of each thread. Suddenly, your program performs background functions that do not require high priority, therefore with the use of a new thread, the user will not perceive any impact on the use;
  3. Security: if there is an error and/or bug happen in the thread main, your program will crash; if it happens on a thread parallel, at most, an error message will be displayed, allowing the user to continue what he was doing.

1

In practice when I use Threads:

  1. When I don’t want to lock my main processing, be it in Forms or on the Web.
  2. When I need performance and the operation does not require dependencies on other operations.

In windows Forms, there is practically no way not to use Multi-thread, because any more time consuming operation hangs the Main Thread, and to access the objects of another Thread, we q use delegates and the invoke method of the Controls!

A good example I used Threads was in the import of data between different databases, where we would deploy a new system in a new company and the company had a legacy system, without using a multi-thread system the import would last about 24 hours, using Thread this time dropped considerably to 35 minutes!

0

We should use threads every time we need to do two tasks at once...

If you have the need to water two Lists first you load and then one and then load the other. With thread you can load them at the same time.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.