简体   繁体   English

跨线程操作在C#中无效?

[英]Cross-thread operation not valid in C#?

I am creating a background worker thread and Loading data in it and showing in UI. 我正在创建一个后台工作线程,并在其中加载数据并显示在UI中。 I know the problem is while showing the data in UI(because it is a UI thread) But i get the data from server in form of blocks . 我知道问题是在UI中显示数据时(因为它是UI线程),但是我以块的形式从服务器获取数据。 Suppose for the first time receive 10 records then i have to update the Ui and then call the next records. 假设第一次收到10条记录,那么我必须更新Ui,然后调用下一条记录。

How to resolve this Issue ? 如何解决这个问题? Thanks. 谢谢。

If you are using a BackgroundWorker you have to make use of the report progress feature. 如果使用的是BackgroundWorker ,则必须使用报告进度功能。

What I usually do is to do the work required inside the DoWork method, and when you want to update the GUI, call worker.ReportProgress with the needed data. 我通常要做的是在DoWork方法中完成所需的工作,并且当您想更新GUI时,请使用所需的数据调用worker.ReportProgress Then in the report progress method, update the GUI since that method will be run on the GUI thread. 然后,在报告进度方法中,更新GUI,因为该方法将在GUI线程上运行。 Also make sure you set WorkerReportsProgress to true, else you will get an exception when trying to call ReportProgress . 还要确保将WorkerReportsProgress设置为true,否则在尝试调用ReportProgress时会出现异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM