简体   繁体   中英

Deleting child object from parent when something happens in child's internal thread

Let's say I have ObjectA (of classA ), which contains:

List<classB> bList;

now let's suppose that in each objectB there are a couple of threads which are running (they can't be accessed from outside objectB ), threadB1 and threadB2 .

Now, in a certain objectB of such list, threadB2 discovers that objectBRemove==true .

When that happens, I want to terminate all threads from such object and remove it from bList (I effectively want to destroy this objectB ).

I thought I could rise an event inside objectB and subscribe a objectA 's method to such event:

public void onObjectBRemove(object sender, EventArgs e)
{
    bList.Remove((classB) sender);
}

When this is called after objectB 's event rising this should remove objectB from the list. Then, the garbage collector should notice objectB becoming unreferenced and thus deleting it, also terminating all internal threads.

Is this supposed to work? Is this a reasonable approach to the problem at hand?

When this is called after objectB's event rising this should remove objectB from the list. Then, the garbage collector should notice objectB becoming unreferenced and thus deleting it, also terminating all internal threads.

This will remove the object from the list - but List<T> is not thread safe, so you'll need synchronization (or a thread safe collection, such as ConcurrentBag<T> ).

Note that this won't terminate running threads. If you want to stop an operation that's running, you should use .NET's cooperative cancellation and set a CancellationTokenSource to it's canceled state, at which point your thread can exit itself gracefully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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