Use one thread to process your request and insert work items for the stream from your event.
Namely:
- copy e
- create a list of <CustomEventArgs> and insert a copy at the end
- synchronize access to this list from the stream and from the event
As a member of the class, do the following:
List< CustomEventArgs > _argsqueue; Thread _processor;
In the constructor of the do class:
_argsqueue=new List< CustomEventArgs >(); _processor=new Thread(ProcessorMethod);
Define processormethod:
void ProcessorMethod() { while (_shouldEnd) { CustomEventArgs e=null; lock (_argsqueue) { if (_argsqueue.Count>0) { CustomEventArgs e=_argsqueue[0]; _argsqueue.RemoveAt(0); } } if (e!=null) { DoLongOperation(e); } else { Sleep(100); } } }
And in your case:
lock (_argsqueue) { _argsqueue.Add(e.Clone()); }
You will need to deal with the details for yourself, for example, when you close the form or when deleting the object in question, you need to:
_shouldEnd=true; _processor.Join();
source share