0

I'm starting new thread for every different job. I think it is better way. But with my coworker we have some conflict about using thread or task. He think Task is more efficient. But there is no reason for this.

We have one Thread start code and another Task run code.

Thread thread = new Thread(() =>
SomeMethod()
);
thread.Start();

// OR


Task.Run(() =>SomeMethod());

Still I think, thread is more efficient for better resource use. Task is high level class and use more resources from main thread (i think). Really do you have any information one is more efficient than other. With really correct reason!

wikiCan
  • 449
  • 3
  • 14
  • 3
    A task will reuse a thread from the thread pool if it can, rather than creating a new one, so `Task` is more efficient. There's very few reasons to use `Thread` nowadays. (Perhaps if you want to create a STA thread rather than an MTA one, but not much other than that.) – Matthew Watson Nov 06 '19 at 10:39
  • 1
    Depends on what you are doing. If your intent is to perform _asychronous I/O_ then a `Task` **won't use a thread at all**. https://blog.stephencleary.com/2013/11/there-is-no-thread.html –  Nov 06 '19 at 10:52
  • @TheodorZoulias I complete some database insert operations (so take long time) with this interface class. just this. I was think we should create different thread for every different job, But now I think Task is more efficient really. – wikiCan Nov 06 '19 at 11:15
  • 1
    _"...some database insert operations..."_ - definately wan't to use async I/O then - use a `Task` –  Nov 06 '19 at 11:19
  • 1
    @wikiCan remember, tasks may not block. If you communicate with the database in synchronous way, that is, call some operations which return result from database and so block the thread while waiting for the reply from the database, then you have to use threads. – Alexei Kaigorodov Nov 06 '19 at 11:20
  • @AlexeiKaigorodov yes it is correct view. If we need to suspend other threads for wait until some result. There is no way on the Task, bu we can suspend and resume threads. Thank you for comment. Yes. – wikiCan Nov 06 '19 at 11:27
  • A `Task` is a class with a size around 50 bytes. A thread has a stack size around 1 MB. So it is possible to create 1,000,000 tasks (it is blazingly fast actually), but it is not possible to create 1,000,000 threads (unless you own a supercomputer with 1 TB RAM). Based on this you should always prefer to create `Task`s instead of `Thread`s. Of course things are more complicated because the tasks are using thread-pool threads under the hood. They use them heavily when the workloads are CPU bound, or sparingly when the workloads are IO bound. – Theodor Zoulias Nov 06 '19 at 12:24

0 Answers0