ben.biddington

With respect to the recommended asynchronous patterns (IAsync and event-based), is there anything wrong with simply registering for an event which will be raised from a worker thread

Suppose I have a class with a member Execute, which raises event ExecuteComplete when done.

If I then wish to run Execute in its own thread, can I still consume ExecuteComplete

This means the event handler is running in the newly created thread.

This kind of approach does not seem to fit with any of the recommended patterns, so I figure it's flawed in some way.

I guess it does put all async operation handling onus on the client class, rather than the object providing the async operation.

There are problems with exceptions raised during Execute too I suppose.

Thanks


Re: Visual C# General Events across threads

micvos

You can use events in threads. That should not be a problem. It's just like any other method you call. But you do have to be carefull about concurrency problems. Make sure you can't use resources at the same time for example.




Re: Visual C# General Events across threads

Peter Ritchie

It's quite common for events to be raised/handled on a different thread. For the most part it doesn't matter. When you're handling events on a Control (e.g. a Form) you have to make sure you don't do anything with the controls from a thread other than the main/GUI thread. You can detect if you're not on the main/GUI thread for a control via the InvokeRequired property. The pattern would be the InvokeRequired/BeginInvoke pattern. There's lots of detail about using that on the Net. If you have specific questions, let us know.

If you want to perform some logic in a background thread and you do have to think about updating controls either during processing or when the processing is completed, I would suggest using the BackgroundWorker class. The BackgroundWorker class provides the ability to perform logic on a background thread while supporting both progress and completed events. The progress and completed events are guaranteed to be executed on the thread that called the BackgroundWorker's RunWorkerAsync method. So, you don't have to deal with the InvokeRequired/BeginInvoke. BackgroundWorker doesn't do anything for synchronization of shared resources though, so you still have to deal with that. Again, there's lots of examples of using BackgroundWorker kicking around; but, if you have specific questions, let us know.




Re: Visual C# General Events across threads

Emilio...

I have a data grid exporter component which I call using BWC and that component raises events - RowExporting, ExportComplete etc.

I ended up having to use if(InvokeRequired) to sync back to the UI thread when hooking to the events raised by the long running process, because that is the BWC thread...

I'm not sure what's the best way to consume those events from BWC thread where I can call ReportProgress

Thank you in advance!