Reputation:
I read here:
.NET async, can a single thread time-slice between tasks?
that, unless you explicitly use async/await, tasks will not "time-slice" on the same thread in the backend thread-pool. Is this guaranteed? Or merely a side effect of the current implementation of the TPL?
If not guaranteed, it would cause problems with using lock()
:
Consider two Tasks which access a method that locks
on a full SerialPort transaction (send a message and receive, or timeout) before releasing. If time-slicing occurs on the same thread and the SerialPort access is slow enough, the lock
would fail to do its job (letting both calls through, because they are technically on the same thread).
Upvotes: 3
Views: 9710
Reputation: 244767
Yes, as long as you don't do anything that makes (some parts of) your code execute on another thread (await
, Task.Run()
, Task.ContinueWith()
, Thread
, …), then it's safe to use lock
or another thread-based synchronization mechanism.
One possible exception is if you have a custom TaskScheduler
(e.g. TaskScheduler.FromCurrentSynchronizationContext()
) and you somehow make that scheduler try to execute more Task
s while your Task
is still executing (e.g. something like Application.DoEvents()
). In that case, your Task
still won't move to another thread, but it may be paused while another Task
executes on the same thread. But this situation should be exceedingly rare.
Upvotes: 1