When and why should we use threads?

1

When and why should we use threads? I would like some examples.

    
asked by anonymous 01.08.2016 / 20:05

3 answers

3

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

  • Long-running functions: Sometimes we have to invoke some function that takes some time to execute. If you do not create a new thread , this function will run on the main main thread, or thread , and it will appear that your program has stopped answer;
  • Non-priority functions: You can set the priority of each thread. Suddenly, your program performs background functions that do not require high priority, so with the use of a new thread, the user will not notice any impact on the use;
  • Security: If any error and / or bug happens in the main thread , your program will crash; if it happens in a parallel thread, at most an error message will be displayed, allowing the user to continue what he was doing.
  • 01.08.2016 / 20:47
    0

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

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

        
    02.08.2016 / 15:23
    0

    In practice when I use Threads:

  • When I do not want to stop my main processing, either in Forms or Web.
  • When I need performance and the operation does not require dependencies on other operations.
  • In Windows forms, there is practically no way to use Multi-Thread, because any more time-consuming operation will lock the main Thread, and to access the objects of another Thread, we have to use delegates and the invoke method of the controls! p>

    A good example that used Threads was to import data between different banks, where we would deploy a new system in a new company and the company had a legacy system, without using a multi-threaded system the import would last around 24h, using Thread this time dropped considerably to 35 minutes!

        
    02.08.2016 / 17:05