开发者

C# Winform Multithread sequence

Am relatively new to C# and coding in general. I am trying to write a program that has some logic and that also ind开发者_C百科icates progress with a progressbar. I am starting a thread in Main() that does all my business logic. It has events that are trigerred at points that I need the progress bar udpated.

The Form object subscribes to the business logic events and has thread safe delegates that are invoked to update the progress bars and text labels.

My problem is that, as the Form is started in the main thread, I have to start the business logic thread before Application.Run(). When the first ProgressUpdate event is trigerred, the Form object still does not exist. I guess a hacky way is to add Thread.Sleep(100) in the second thread, but I don't like that. How do I get around this? Am I on a completely incorrect track? (Am I even making sense?)

        Form1 theForm = new Form1();
        CreateReport theCreateReport = new CreateReport();
        Thread t = new Thread(new ThreadStart(theCreateReport.DoProcess));
        t.IsBackground = true;
        theForm.Subscribe(theCreateReport);
        t.Start();
        Application.Run(theForm);

theForm is the form. theCreateReport is where my business logic starts.


You want to use one or more BackgroundWorker objects instead of your business logic thread. This will manage the threading for you as well as giving you a way to provide progress feedback to the main thread.


Maybe you should start your business logic in OnLoad event?


The Form already exists after you invoke the constructor (on the very first line) - it's just not visible yet. So you don't need to worry, everything is initialized when you start the new thread.


In Main, just create the form and Application.Run it. In the Load event of the form, start your thread.

You don't really gain any advantage from doing things the way you're currently doing them. And as you've already found, it creates a timing/sequence problem.

The best way to fix problems is to not have them in the first place.


I would use BackgroundWorker and you can still use your events and delegates with it. This time round you will be wrapping up and firing Background Worker's "ProgressChanged" and "RunWorkerCompleted" events.

And you Form can listen to these events and update ProgressBar accordingly.

BWorker handles switching to GUI Thread and Exception Handling better.

You can initialize BackgroundWorker on Form Load.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜