开发者

Continously updating a form from a background thread

开发者 https://www.devze.com 2023-02-18 23:33 出处:网络
Suppose I have some information received on asynchronous sockets (thereforeexits some background threads) , that continuously update a form. How could I safely update the form content so that I avoid

Suppose I have some information received on asynchronous sockets (therefore exits some background threads) , that continuously update a form. How could I safely update the form content so that I avoid the ObjectDisposedException that is sometim开发者_开发知识库es thrown when I close the form ?

In the update operation (carried on the background thread) I check for the form's property IsDisposed, but this is useless as the UI thread sometimes disposes the form immediately after the check and right before the update operation causing the exception to be thrown (when I close the form) I've tried to use a lock on the form object in the form's "onScreenFormClosed" handler and on the update operation to ensure that these operation are not executed simultaneously , but this blocks the UI thread .

I even tried to run the update operation on the UI thread, but it was to no use as calling Invoke(...) on the form still throwed the ObjectDisposedException .


Can you alter the classes that are generating the background threads? I'd have them watch for the appropriate events on the form and check if the form has closed at the start of the update information.

C# uses events and delegates to implement the observer and observable pattern but then it doesn't matter how many forms are being updated only those that are still observing will be updated.

http://social.msdn.microsoft.com/Forums/en-US/csharplanguage/thread/11b46013-089b-44ca-907a-6dab05c5b454/


I handled this by doing the following :

In the OnClose event of the UI Form I sent a "we are exiting" command to the background threads so they would stop operations, and then sleeping the UI thread for a short period to allow the background threads to close, it works nicely for me, but may not applicable in all circumstances.

0

精彩评论

暂无评论...
验证码 换一张
取 消