当前位置: 动力学知识库 > 问答 > 编程问答 >

vb.net - Is it possible to update the UI from the backgroundworker dowork event

问题描述:

I have seen others with a similar issue but not quite what I was looking for. In the backgrounderworker class dowork event I create an instance of a new class and call one of it's function. Previously, I had this code in a windows.form.timer tick event and would pass a delegate in as one of the parameters which would allow the function and other functions it calls within the class to call a method on the form to update a datagrid on the GUI. Is there a way to do this within the dowork event? I need this because the function I call from dowork calls other functions and I want each of those functions to log information in the GUI datagrid.

网友答案:

The BackgroundWorker.ReportProgress() method was intended to do that. You implement the ProgressChanged event to update the UI, it will run on the main thread. You're not restricted to report just a progress percentage, you can pass any object as well to pass info to the event handler by using the overload that accepts the userState argument. Beware that you have to use proper locking if you do that.

网友答案:

Apart from ReportProgess mentioned in Hans' answer, you can alternatively use Control.Invoke on one of the UI elements to exeute code in the UI thread.

网友答案:

You can send progress data back to the UI thread, you will get an event for that on the UI thread, then you can update the screen. It is highly preferred that the objects you send back to the UI thread are immutable. Besides calling the ReportProgress and handling the event you need to opt-in by setting WorkerSupportsProgress property to true.

分享给朋友:
您可能感兴趣的文章:
随机阅读: