Link to home
Start Free TrialLog in
Avatar of brenlex
brenlexFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Graceful detruction of object containing thread.

I have an arraylist MyList of MyMonitored objects. Within the MyMonitored class is a running thread object.

What is the best practice to remove the MyMonitored instance from MyList? Can I just remove the MyMonitored instance from MyList and let GC handle it, or do need to ensure the thread running within the object has stopped first?  If so, can I just to this within the MyMonitored class's destructor?
Avatar of s_chilkury
s_chilkury
Flag of United States of America image

Avatar of brenlex

ASKER

Thanks, but not really.  I do not need the thread to invoke any activity outside of its own scope of the instance in which it is run.  I just need to remove the instance of MyMonitored from MyList and be confident that the MyMonitored object destroys itself properly (i.e. the threaded process running within the MyMonitored object has stopped first).

I could expose a public bool var 'HasStopped' within the MyMonitored class and run a while loop before I remove it from MyMonitored list, but I am sure there is a better way...
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I made a typo, line 92 should be if (disposing), also (if you use a Collection<T>) make sure you override ClearItems() as well.
Avatar of brenlex

ASKER

Thanks tgerbert, but my MyList object is already an instance of an existing threadsafe class which encapsulates an arraylist.  I have gone for the option of using ManualResetEvent to stop the thread, which in turn reports via callback when gracefully stopped, allowing me to destroy MyMonitord instance.

I shall try out your recommended method in the near future (for a similar project) though.  Hence point split.

Many thanks.