开发者

WPF BackgroundWorker - UI locks up trying to instantiate object from external class

I am trying to run a backgroundworker to load data from my DAL (which is available in another class). I want to keep the UI available and not have the "locked up" feel while the object is loading.

When I create a simple backgroundworker and Sleep the UI stays responsive and my controls can be updated after the sleep. As soon as I replace the sleep with a call to instantiate the object from my DAL, the UI locks up. Is there someway I can instantiate this object using the background worked and keep the UI responsive?

When the situation object is instantiated it could take several seconds for it to load completely, during this time is when the UI is locked up... It does eventually load just fine.

Private WithEvents backWork As New BackgroundWorker()
Dim sit As Situation

Private Sub btnLoad_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnLoad.Click

    backWork.RunWorkerAsync()

End Sub

Private Sub backWork_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles backWork.DoWork
    Load()
End Sub

Private Sub backWork_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEv开发者_开发问答entArgs) Handles backWork.ProgressChanged
    lblLoading.Visibility = Visibility.Visible
End Sub

Private Sub backWork_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles backWork.RunWorkerCompleted
    tab1.DataContext = sit
    lblLoading.Visibility = Visibility.Hidden
End Sub

Private Sub Load()
    backWork.WorkerReportsProgress = True
    backWork.ReportProgress(1)

    sit = New Situation

End Sub


http://msdn.microsoft.com/en-us/library/hybbz6ke.aspx

I would start with the above link, more specifically a comment in the sample code: ' Do not access the form's BackgroundWorker reference directly. ' Instead, use the reference provided by the sender parameter.

You'll have to pass that reference to the Load() method. And as a general rule don't access anything directly on the parent thread. All the communication needs to happen through the instances of various EventArgs parameters.

Unless you understand DoWorkEventArgs, ProgressChangedEventArgs, RunWorkerCompletedEventArgs you will not really understand how to use Background worker

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜