Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To thread or not to thread

I'm building a rather simple application that performs a few seperate HTTPWebRequests, each on their own timer. It's not likely I will need to have more than 3 seperate requests running at a time.

If a Timer Tick fires while another HTTPWebRequest is in progress, what happens to the event fired by the Timer Tick? Should I add Threading?

like image 922
Mr Wednesday Avatar asked Mar 13 '12 22:03

Mr Wednesday


People also ask

Why threads are a bad idea for most purposes?

They are “too hard for most programmers to use, and even for experts development is painful.” Threads are hard because: You have to explicitly coordinate access to shared date with locks. If you forget a lock, you'll end up with corrupted data.

When would you choose process over the thread?

When it comes to processes, the OS usually protects them from one another. Even if one of them corrupts its own memory space, other processes are not affected. Another benefit of using processes over threads is that they can run on different machines. On the other hand, threads normally have to run on the same machine.

Why do we need threads?

On a multiprocessor system, multiple threads can concurrently run on multiple CPUs. Therefore, multithreaded programs can run much faster than on a uniprocessor system. They can also be faster than a program using multiple processes, because threads require fewer resources and generate less overhead.

What is thread with example?

Thread is often referred to as a lightweight process. The process can be split down into so many threads. For example, in a browser, many tabs can be viewed as threads. MS Word uses many threads - formatting text from one thread, processing input from another thread, etc.


2 Answers

The answer is almost always - no, don't use threads just because you can.

Consider making asynchronous calls first as it is easier to write correct code for. It is likely more efficient use of resources (as threads are not unlimited resource) if you need additional arguments.

Links:

  • How to use HttpWebRequest (.NET) asynchronously?
  • Use async methods of WebClient like WebClient.DownloadStringAsync
like image 161
Alexei Levenkov Avatar answered Oct 20 '22 06:10

Alexei Levenkov


When Timer.Tick fires it's handler will be scheduled for execution in Thread Pool and most likely, executed in another thread.

like image 1
the_joric Avatar answered Oct 20 '22 06:10

the_joric