I have an object that can take anywhere from two seconds to several minutes to initialize. The reason is that the designer is retrieving data from the web service, which can range from a few kilobytes to several megabytes, and depending on the connection speed of the user connection, the speed can vary greatly. For this reason, I want to put events in this to handle the progress notification.
Here is my question: can I put an event handlers in the constructor or should this type of action have to be performed using the Load Method?
For example:
public class MyObject { public event EventHandler<UpdateLoadProgressEventArgs> UpdateLoadProgress; public MyObject(int id) { Background worker bgWorker = new BackgroundWorker(); bgWorker.DoWork += delegate(object s, DoWorkEventArgs args) {
However, when I try to associate event handlers with the constructor, they are always zero when called:
MyObject o = new MyObject(1); o.UpdateLoadProgress += new EventHandler<EventArgs>(o_UpdateLoadProgress);
I assume this is happening because I am hooking events after the constructor. The only alternative that I see is to create a Load method that does the work of the constructor. The disadvantage is that anyone using this class must know to call Load before trying to access the Result (or any other property).
EDIT: Here is the final solution:
Class MyObjectBuilder
public class MyObjectBuilder { public event ProgressChangedEventHandler ProgressChanged; public MyObject CreateMyObject() { MyObject o = new MyObject(); o.Load(ProgressChanged); return o; } }
Class myobject
public class MyObject { public int Result { get; set;} public void Load(ProgressChangedEventHandler handler) { BackgroundWorker bgWorker = new BackgroundWorker(); bgWorker.WorkerReportsProgress = true; bgWorker.ProgressChanged += handler; bgWorker.DoWork += delegate(object s, DoWorkEventArgs args) { for (int i = 0; i < 100; i++) { Thread.Sleep(10); Result = i; bgWorker.ReportProgress(i); } }; bgWorker.RunWorkerAsync(); } }
Program class
class Program { static void Main(string[] args) { MyObjectBuilder builder = new MyObjectBuilder(); builder.ProgressChanged += new ProgressChangedEventHandler(builder_ProgressChanged); MyObject o = builder.CreateMyObject(); Console.ReadLine(); } static void builder_ProgressChanged(object sender, ProgressChangedEventArgs e) { Console.WriteLine(e.ProgressPercentage); } }
Blake blackwell
source share