开发者

wpf form freezing with get data from database

I created WPF application using c#.I have to get more data in here from mysql databse开发者_JAVA技巧.I'm use for this one ODBC 3.51 connector.when data loading freeze my application. I'm try to fix that problem using thread.But I can't able to do this one using thread. Please suggest to way for solve my problem...


Use a BackgroundWorker-class. It's usage is very simple and it is used quite often for tasks such as loading data. The following example shows you it's usage:

BackgroundWorker bgWorker = new BackgroundWorker() { WorkerReportsProgress=true};  
bgWorker.DoWork += (s, e) => {      
    // Load here your data      
    // Use bgWorker.ReportProgress(); to report the current progress  
};  
bgWorker.ProgressChanged+=(s,e)=>{      
    // Here you will be informed about progress and here it is save to change/show progress. 
    // You can access from here savely a ProgressBars or another control.  
};  
bgWorker.RunWorkerCompleted += (s, e) => {      
// Here you will be informed if the job is done. 
// Use this event to unlock your gui 
};  
bgWorker.RunWorkerAsync();  

The use of the BackgroundWorker allows the UI-thread to continue it's processing and therefore the application rests responsive during loading. But because of this, you have also to ensure that no actions can take place that rely on the loaded data. A very simple solution is to set your main UI elements IsEnabled-property to false and in RunWorkerCompleted you set it to true. With a little fantasy you can improve this dumb behaviour tp a nice UI-experience (depending on the App).

It is general a good a advice to do long time operations in a separate thread (BackgroundWorker). One caveat is there: Do not create WPF-Elements in the DoWork-event. This will not do because all derived types of DependencyObject must be created in the same thread they are used.

There are other solutions to do this, for example creating directly a thread or with the event based async pattern, but I recommend to use BackgroundWorker for your task because it handels for you the plumbing. In the end, the result is the same but the way to it is much easier.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜