2

I am quite new to C# and threading, and I have this problem to resolve:

I have a thread which processes some data and from time to time (when necessary) it fires my event method (DataProcessor) which was set before starting the thread. This thread is in proprietary dll. So I cannot affect DataProcessor calling anymore.

public void DataProcessor(object sender) { //... //do some stuff which take some time } 

My problem is that from time to time when DataProcessor is fired and starts doing some stuff and it's not finished yet, it's fired again and I have a conflict.

What I need is, when DataProcessor is doing some stuff all other data is unnecessary so all other attempts to process another data MUST be ignored/skipped - are not relevant for processing.

1
  • "C#" isn't necessary in the title. We have tags for that on Stack Overflow. Commented Aug 24, 2011 at 5:28

1 Answer 1

1

Event handlers should be used to perform very quick operations. The way I've handled similar situations is when the event fires, to put some "to-do" item inside a queue. I then run a continuous thread that handles items from the queue.

A good way to simplify this operation is to use BlockingCollection. Your thread simply runs a foreach over that collection, which will block waiting on enqueued items.

You can also unsubscribe from the event when you are inside your handler, and resubscribe when you are done processing, but you will lose events this way.

Sign up to request clarification or add additional context in comments.

3 Comments

"A good way to simplify this operation is to use BlockingCollection. Your thread simply runs a foreach over that collection, which will block waiting on queued items." I don't quite understand this. Do you mean, to use locker do lock inside the DataProcessor and then remove all other items in waiting queue? Could you please write an example? I need a simplest and fastest solution for this, because I need to process as many data as possible. Don't ask me why do I need to throw any other data occurred meanwhile DataProcessor is running, it must be done like that. Thanks.
If you need to ignore events that occur while you're processing, then ignore the first part of my answer, and simply unsubscribe from the event: myevent -= (s, e)=> DataProcessor(s); or your equivalent (just change the += you use to subscribe to a -= to unsubscribe). When the processing is over, re-subscribe.
removing handler via -= seemd to be a good solution, until I've put my application to the real environment, where is fireing of handler so often, that meanwhile I was removing handler via -= it started to run handler again and caused app freeze, so how could I serialize (or rather ignore other events) that?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.