views:

187

answers:

2

I want to use a BackgroundWorker or a Thread to call a method from my windows form on a class located in my business layer. I would like the method in this business layer to be able to report its progress if anyone is listening as it may take awhile to complete. Since I may start with a BackgroundWorker and later decide to use a regular thread, I don't want to get tied to either.

What would be the best way for a method to report its progress if its unaware of the if it was called by a backgroundworker? I was thinking of providing an event on my Business Layer Class that could publish its progress should anyone be listening.

Is there a delegate in the Framework already for that? Better Yet an Interface that I could Implement - something like INotifyProgressChanged?

A: 

I believe you are going the correct direction with firing an event handler, you can declare an event in your class (using VB, C# is similar of course) as such:

Public Event foo(ByVal progressVar1 As Double, ByVal progressVar2 As String)

then add some handlers to it on your winforms. The problem that arises here is that the fired events will execute on the same thread as thebackground worker or thread, so you'll still have to use the Invoke() method to actually mess with the UI.

Jrud
A: 

You could utilize BackgroundWorker, here are some events that you can subscribe,

   bgObj.DoWork += (sender, e)=>{ // do something in your business layer} 
   bgObj.RunWorkerCompleted += (sender, e)=>{ // do something}
   bgObj.ProgressChanged += (sender, e)=>{ // do something}

Alternatively, you can declare public events within your business layer (Does the actual work), and raise the events at appropriate places so that the subscriber( say from the form ) can get the notifications.

(Note apart from UI thread, you may not be able to update the UI control, check out control1.BeginInvoke method)

codemeit