1

I have the situation that I need an exclusive singleton for each task I run. Currently I use [ThreadStatic] attribute to keep the singleton's instance for each thread separately. But: Can I count on that more than one task is never run in same thread at same time? ... otherwise my singleton would be shared between these tasks.

Filburt
  • 17,626
  • 12
  • 64
  • 115
user1470240
  • 580
  • 3
  • 19
  • I'd recommend having a read of [this](https://stackoverflow.com/questions/37419572/if-async-await-doesnt-create-any-additional-threads-then-how-does-it-make-appl) – ProgrammingLlama Mar 16 '18 at 08:08
  • It would be more readable to pass expected values as parameters to async method instead of using singletons. – FCin Mar 16 '18 at 08:14
  • 1
    Depends to a great extent on *how* the `Task`s are going to be completed which is very much an implementation detail that deliberately isn't really part of the `Task` contract. `Task` objects are an abstraction for ongoing work. For instance, it's perfectly valid for a thread to be running some code in which it has an array of `TaskCompletionSource` objects and marks each one as complete in a loop. Does that mean that all of those tasks were "running" on that thread? That's a philosophical question. – Damien_The_Unbeliever Mar 16 '18 at 08:43
  • Just out of curiosity, if each task needs its own 'singleton', why not use a separate class for each task which contains its own properties? The Task start point could be a method in the class. Or is the static field also used by methods outside the task? – Me.Name Mar 16 '18 at 09:27

1 Answers1

1

I assume you are talking about CPU bound tasks e.g. Task.Run and equivalent.

The TPL can inline tasks in a variety of circumstances. This can cause multiple tasks to be on the same thread and stack. For example, Task.Wait can run the task argument if it has not been started and the scheduler allows it.

The TPL is absolutely full of such reentrancy where a seemingly harmless call such as Task.Wait or TaskCompletionSource.SetResult can run arbitrary code. This is in my view a very nasty design bug. And it's causing lots of practical issues. I'm sometimes reading the coreclr/corefx commit logs and I regularly find bug fixes there for issues causes by TPL reentrancy.

usr
  • 168,620
  • 35
  • 240
  • 369
  • I see, this means, it can happen, that the task objects can exist side by side in the same thread. I think I have to reconsider my design again (either using thread class instead task class or passing all stuff around ..). Thank you! – user1470240 Mar 16 '18 at 12:05