Andrew Stephens
Andrew Stephens

Reputation: 10203

How to handle events on a background thread?

I have a class that fires an event at a fairly rapid frequency (every 100ms). To avoid slowing down this process, event handlers should hand off the processing to some kind of background task/thread/worker (as opposed to doing it within the event handler).

What's the best approach? Should I use Task.Factory.StartNew within the event handler? Will there be an overhead of creating tasks this rapidly (e.g. 5 event handlers will create 5 tasks every 100ms)? Or could I use a BackgroundWorker (instantiated in a subscriber's constructor), and in the event handler call the .RunAsync method?

Upvotes: 2

Views: 1143

Answers (1)

Kevin Gosse
Kevin Gosse

Reputation: 39027

Two ways:

  • Either use Task.Factory.StartNew. This method relies on the ThreadPool to minimize the task creation cost. This should be ok in most cases.
  • If you need to further reduce the performance impact, you can create a producer/consumer queue. When the event is triggered, enqueue a notification. On the other side, a thread monitors the queue and process the notifications as they arrive.

Upvotes: 4

Related Questions