简体   繁体   English

访问列表项时,UI和辅助线程同步

[英]UI and Worker thread synchronization when accessing List item

I have a List which has data to process. 我有一个要处理数据的列表。 And I have 2 threads, 我有2个线程,

UI Thread : Updates/Adds the List item, UI线程:更新/添加列表项,

Thread 1 : Once item added into list it sends the item one by one to another thread 2, 线程1:将项目添加到列表后,它将一个项目一个接一个地发送到另一个线程2,

Thread 2 : Does it's work and updates the item accordingly and Once it completes it's work, it checks list and if the corresponding item still exists in the list, If it exists it process the data. 线程2:它是否正常工作并相应地更新该项目,一旦完成工作,它将检查列表,并且列表中是否还存在相应的项目;如果存在,它将处理数据。

From UI thread when closing the window, I am removing the items from map which are added from the UI. 当关闭窗口时,从UI线程中,我将从地图中删除从UI添加的项目。 So that the thread 2 won't proceed the items which are removed from list. 这样线程2就不会继续执行从列表中删除的项目。

And from the UI destruct or, I am deleting the item instances which are added in list. 并从UI销毁,或删除列表中添加的项目实例。

The issue is, Thread 2 is already processing an item, In the mean time Window is closed and also the destructor deleted the item which is in processing by thread 2. 问题是,线程2已经在处理一个项目,与此同时,窗口已关闭,析构函数也删除了线程2正在处理的项目。

So the processing of the data by the thread 2 crashes. 因此线程2对数据的处理崩溃。

I have done this in MFC. 我已经在MFC中完成了此操作。 How to synchronize these 2 threads (UI deletion and Thread 2). 如何同步这两个线程(UI删除和线程2)。 I know there are different Thread synchronization methods in MFC. 我知道MFC中有不同的线程同步方法。 Which method is best for this scenario? 哪种方法最适合这种情况?

When you want to halt the operation (perhaps when the user clicks the Close button), first you tell the thread to exit. 当您想要停止操作时(也许在用户单击“关闭”按钮时),首先您告诉线程退出。 That can be done with a bool or a event (SetEvent) that the thread checks regularly. 这可以通过线程定期检查的布尔值或事件(SetEvent)来完成。 After you tell the thread to exit you must not delete the UI or any data being used by thread until you are sure the thread has exited. 告诉线程退出后,在确定线程退出之前,不得删除UI或线程正在使用的任何数据。 Use the thread handle in WaitForSingleObject to wait for the thread to exit. 使用WaitForSingleObject中的线程句柄等待线程退出。 WaitForSingleObject suspends the calling thread until the thread handle signals that the thread has exited. WaitForSingleObject暂停调用线程,直到线程句柄发出该线程已退出的信号。 Then you can continue the delete and UI shutdown. 然后,您可以继续删除和关闭UI。

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

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