0

I'm really loving the TPL. Simply calling Task.Factory.StartNew() and not worrying about anything, is quite amazing.

But, is it possible to have multiple Factories running on the same thread? Basically, I have would like to have two different queues, executing different types of tasks. One queue handles tasks of type A while the second queue handles tasks of type B.

If queue A has nothing to do, it should ignore tasks in queue B and vice versa.

Is this possible to do, without making my own queues, or running multiple threads for the factories?

To clarify what I want to do.

I read data from a network device. I want to do two things with this data, totally independent from each other.

  1. I want to log to a database.
  2. I want to send to another device over network.

Sometimes the database log will take a while, and I don't want the network send to be delayed because of this.

Nicolai
  • 2,835
  • 7
  • 42
  • 52
  • [StartNew is Dangerous](http://blog.stephencleary.com/2013/08/startnew-is-dangerous.html) – Sriram Sakthivel Mar 04 '14 at 08:07
  • You are going to need a custom scheduler. A `Factory` simply builds the `Task` - a scheduler actually queues it. What are you trying to achieve. Perhaps there is more straight forward way of achieving it. – Gusdor Mar 04 '14 at 08:07
  • @SriramSakthivel `Task.Run` does not exist prior to .net 4.5... – Gusdor Mar 04 '14 at 08:08
  • @Gusdor Fine, You can specify all necessary parameters mainly the scheduler, or create your own factory with parameters defined once! That's not too hard – Sriram Sakthivel Mar 04 '14 at 08:10
  • The power of TPL isn't in threads. The most powerful aspect come from pure callback I/O. Unless you really are CPU bound, stick to using `Task.Factory.FromAsync` – Aron Mar 04 '14 at 08:17
  • @Aron that really only works if you have an Asynchronous Programming Model pattern entry point defined - replaces this pattern. – Gusdor Mar 04 '14 at 08:52
  • Are you sure this is actually going to be a problem for you? Even if a single database log takes too long, the network work will most likely execute at the same time on another thread. – svick Mar 10 '14 at 19:07

2 Answers2

0

You can define yourself a thread pool using a queue of threads

0

If you use .NET 4.0:

  • LimitedConcurrencyLevelTaskScheduler (with concurrency level of 1; see here)

If you use .NET 4.5:

  • ConcurrentExclusiveSchedulerPair (take only the exclusive scheduler out of the pair; see here)

Create two schedulers and pass them to the appropriate StartNew. Or create two TaskFactories with these schdulers and use them to create and start the tasks.

Community
  • 1
  • 1
Eli Arbel
  • 22,391
  • 3
  • 45
  • 71