开发者

Is this way of threading inefficient in WPF/C#?

Is doing this less efficient than setting up a background worker thread? Because it is working well and seems cleaner. In the loop I am calling BeginInvoke 3x - to add rows to main window datagrid, and to update the progress bar and message.

public MyConstructor()
{
    InitializeComponent();

    ThreadStart sta开发者_如何学运维rt = delegate()
    {
        for (...)
        {
            ...
            MyWindow.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                new Action(delegate()
                {
                    // Do something on the MyWindow thread.
                }
            ));
            ...
        }

        // Intensive loop now done and we close this processing window.
        this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
            new Action(delegate()
            {
                this.Close();
            }
        ));
    }; // ThreadStart

    new Thread(start).Start();
}


It doesn't exactly look clean to me...
But other than that, I see no reason for not doing it. But I also do not see a reason, for not using the BackgroundWorker:

private void BWDoWork(...)
{
    for (...)
    {
        // ...
        worker.ReportProgress(...);
    }
}

private void BWReportProgress(...)
{
    // do something on the MyWindow thread
}

private void BWCompleted(...)
{
    this.Close();
}

It looks cleaner to me, because you have a little separation of the real work that is done in the thread and the UI updating...


It's OK-ish, but a few points:

  • You should probably be setting IsBackground on the Thread object, so that it doesn't cause your application to hang at exit.
  • If this is a short-running activity, then you shouldn't create a new thread, instead use ThreadPool.QueueUserWorkItem or the new 'Task' stuff on .NET4.
  • If there's an unhandled exception on your background thread (either pool or manually created), the app's going to fail with very little you can do about it. Things like 'Task' handled that better.

You don't really qualify 'efficient' very clearly, but BackgroundWorker is generally a better way of doing this sort of thing - if nothing else, it will use a pool thread, which is much cheaper than a manually created thread.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜