Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use GC.KeepAlive() and for what purpose?

How can we use GC.KeepAlive() and what is the purpose?

I transfer files from terminal (Windows-CE) to Server using Socket. The time needed for transfer is 8 minutes. After 5 minutes the Windows-CE shuts down (if touch screen not pressed)

If I use GC.KeepAlive() for this, does this solve my problem?

like image 695
Gali Avatar asked Sep 03 '11 18:09

Gali


2 Answers

You very rarely need to use GC.KeepAlive - very rarely. You'd use it if you wanted to prevent the side-effect of a finalizer from occurring too early, for example. I've most often seen it used for Mutex - keeping mutex alive until the end of an app to make sure there's only one instance. (A using statement is actually better here, but that's a separate matter.)

And no, it doesn't sound like it's relevant in your situation.

like image 56
Jon Skeet Avatar answered Oct 19 '22 01:10

Jon Skeet


From the MSDN library for .NET:

The purpose of the KeepAlive method is to ensure the existence of a reference to an object that is at risk of being prematurely reclaimed by the garbage collector. A common scenario where this might happen is when there are no references to the object in managed code or data, but the object is still in use in unmanaged code such as Win32 APIs, unmanaged DLLs, or methods using COM.

So not this would not solve your problem. In fact it's not even related to your problem. The only thing you can do is in the service/application running on the Windows CE, adding code that prevents the system to shutdown as long as the transfer is in progress

like image 36
codingbunny Avatar answered Oct 19 '22 00:10

codingbunny