1

I have a main class which does some operations and another class which communicates with a server using a socket.

Does creating a object of the socket class in the following manner makes all the operations in the socket class run on a separate thread?

await Task.Run(()=>socketObj.initializeSocket());

Or is there a another way to launch the class on a separate thread?

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
Illuminati0x5B
  • 602
  • 7
  • 24
  • 3
    What do you mean by *"all the operations in the socket class"*? It makes `initializeSocket` and anything that's called inside that method run on a separate thread. – Matt Burland May 11 '16 at 15:04
  • @MattBurland socket class has methods like Connect(), SendAndReceive() etc. When I invoke these methods, will they be handled by a separate thread? – Illuminati0x5B May 11 '16 at 15:13
  • What does `initializeSocket` do? Presumably it instantiates your socket class. If you then call methods on that object then no, those methods will be called on the thread you called it on. They don't magically get called on the thread that created the object. – Matt Burland May 11 '16 at 16:48

2 Answers2

0

Task parallel library (TPL) uses lot of run-time heuristics to take decisions while scheduling your asynchronous method execution. There is no guarantee that it will always be launched on a separate thread (which is essentially a thread from CLR's thread pool). Once you have used await keyword then it essentially means your main thread is blocked and it can't do any useful work other than waiting for your initializeSocket function to finish before proceeding further. Specially in cases when socket initialization is going to take really really small time then TPL might want to use your main application thread instead of scheduling it on its internal task schedulers. I had some similar doubt few months back and this thread might help:

Real purpose of providing TaskScheduler option through ParallelOptions parameter in Parallel class APIs

More details here :

Is Task.Factory.StartNew() guaranteed to use another thread than the calling thread?

Do not worry about other TPL apis being discussed in these threads instead of Task.Run in your case. A task is a task after all irrespective of the API which creates it. Most of the task scheduler heuristics will remain same once you enter into the world of TPL.

Community
  • 1
  • 1
RBT
  • 24,161
  • 21
  • 159
  • 240
0

Does creating a object of the socket class in the following manner makes all the operations in the socket class run on a separate thread?

No.

Or is there a another way to launch the class on a separate thread?

I'm not sure what "launch the class" means.

The code as you currently have it will call initializeSocket on a thread pool thread. It will not cause all other methods on socketObj to run on thread pool threads.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810