Should I put KeepAlive inside my finally block? - c#

So this tells me that I should put a GC.KeepAlive at the end of my code to keep my mutex open (to prevent multiple instances of my app happening due to early GC disposal of my mutex). But should I put the KeepAlive in my finally block or at the end of my try block?

I personally would not use that approach.
The issue is that you need to have something use the mutex after your Application code (in this case, the form) completes, or it will be a candidate for GC post-optimizations.
Since Mutex implements IDisposable, you can just as easily do this:
[STAThread]
static void Main() // args are OK here, of course
{
bool ok;
using(var mutex = new System.Threading.Mutex(true, "YourNameHere", out ok))
{
if (!ok)
{
MessageBox.Show("Another instance is already running.");
return;
}
Application.Run(new Form1());
}
}
This will work just as well, since the finally created by the using statement will prevent the mutex from being a GC candidate. I, personally, find this less confusing and cleaner code.
That being said, if you want to follow the approach from that link, just putting KeepAlive anywhere will cause the mutex to not get collected, and prevent the issue. You can put it inside your try or finally block - as long as it's after the main application code "completes". You can also ignore this and just explicitly Dispose() the mutex - as long as you use the mutex some way, it will be fine.

Related

Accessing the GUI from a background Thread

I've made a sample program which generates every second 2000 integers on a Background thread, and when it finishes it fires an event which draws graph on the GUI from the random generated data (I have a sleep inside my thread to simulate a real measurement).
private void SetChart(System.Windows.Forms.DataVisualization.Charting.Series series)
{
if (InvokeRequired)
{
SetChartCallback d = new SetChartCallback(SetChart);
this.Invoke(d, new object[] { series });
}
else
{
chart1.Series[0] = series;
chart1.Series[0].Name = "Generated Data";
}
}
I found this approach on the MSDN site. It's working fine, the only problem is, when I close the application. Sometimes an error meassage shows up :
Cannot access a disposed object.
Object name: 'Form1'.
When I close the program it disposes all the elements, how can I prevent this error not to happen?
You've closed the form, but the thread is still running, so when it completes It tries to invoke a method on the disposed object. Your form.
You can wait for the thread to complete.
Or you can signal it somehow to stop messing about creating integers you don't need anymore and quit it's loop right now.
Don't be tempted to just kill it. Very bad habit, you don't want get into that.
The proper approach, ugly as it may seem, is probably to catch the exception and swallow it. It's probably not reasonable for the form's Dispose to block until the background thread exits (a situation which could easily cause deadlock); nor does the Framework provide any method which says try to Invoke or BeginInvoke this method on a control or form, but simply do nothing if it's been disposed. Thus, your best bet is probably to write TryInvoke and TryBeginInvoke methods which will do that by catching any exception that results if the form has been disposed. You might use an IsDisposed check within such a method, but you should realize that because of some Framework quirks, there are some race conditions which cannot be resolved nicely.
A solution may be to check IsDisposed. Something like this:
private void SetChart(System.Windows.Forms.DataVisualization.Charting.Series series)
{
if (IsDisposed)
return;
// ...
}

How do you close an application when some WaitHandle is in the middle of a call to WaitOne?

Is there a standard way to close out an application "cleanly" while some WaitHandle objects may be in the state of a current blocking call to WaitOne?
For example, there may be a background thread that is spinning along in a method like this:
while (_request.WaitOne())
{
try
{
_workItem.Invoke();
}
finally
{
OnWorkCompleted();
}
}
I see no obvious way to dispose of this thread without calling Thread.Abort (which from what I understand is discouraged). Calling Close on the _request object (an AutoResetEvent), however, will throw an exception.
Currently, the thread that is running this loop has its IsBackground property set to true, and so the application appears to close properly. However, since WaitHandle implements IDisposable, I'm unsure if this is considered kosher or if that object really ought to be disposed before the app exits.
Is this a bad design? If not, how is this scenario typically dealt with?
Define an additional WaitHandle called _terminate that will signal a request to terminate the loop and then use WaitHandle.WaitAny instead of WaitHandle.WaitOne.
var handles = { _request, _terminate };
while (WaitHandle.WaitAny(handles) == 0)
{
try
{
_workItem.Invoke();
}
finally
{
OnCompleteWork();
}
}
When a thread is blocking (regardless of what it's blocking on) you can call Thread.Interrupt() This will cause the exception ThreadInterruptedException (I believe, it might be a little different) You can handle this exception on the thread itself and do any neccesary clean up.
It's worth noting, that the thread will only throw the ThreadInterruptedException when it is blocking, if it's not blocking it won't be thrown until it next tries to block.
This is the "safe" way of ending threads from what I've read on the subject.
also worth noting: If the object implements both IDisposable and a finializer (which it will if it uses unmanaged resources) the GC will call the finalizer which normally calls dispose. Normally this is non-deterministic. However you can pretty much guarantee they will get called on application exit. Only under very special circumstances they wouldn't. (A .net environment termininating exception such as StackOverflowException is thrown)
Set the IsBackground property to true... it should automatically close the thread when your app ends.
Alternately, you can interrupt the thread by calling Thread.Interrupt and handle the ThreadInterruptedException. Another idea is to call _request.Set() and make the while loop check a volatile flag to determine if the application is closing or if it should continue:
private volatile bool _running = true;
while(_request.WaitOne() && _running)
{
//...
}
// somewhere else in the app
_running = false;
_request.Set();
I think the operating system will clean up after your process has finished. Because your thread is marked as IsBackground the CLR will end the process and all the threads within, so this is not a problem.

Compact Framework 2.0: How can I stop a thread when an object is dispose?

I have this code:
Thread t = new Thread(() => UpdateImage(origin));
t.Name = "UpdateImageThread";
t.Start();
This code is created on a Custom Control. I want to stop this thread (if it's running) when the object is going to be dispose.
This custom control has the following method:
void IDisposable.Dispose()
{
/* My own code */
base.Dispose(true);
}
I think this is the place to put the code but:
How can I know is the thread is running?
How can I take a referece for the thread and stop it?
By the way, UpdateImage call a web service, so I think that it's waiting all of its life.
How can I finish this wait?
Thank you!
It depends a lot on what UpdateImage() does and how well it copes with the Image being disposed while it it still active. If UpdateImage() is your code and contains a loop you can tell it to stop (using a field like _stopping). If not, the best thing may be to do nothing - in the rare case of Disposing the control while the image is still updating you take the penalty of leaving it to the GC.
About how to get the Thread: By saving the reference when and where you create it, for instance int the private member _updateThread.
Now actually stopping (aborting) the thread is a (very) bad idea.
So you'll need an indicator, like
private bool _stopping = false;
And it is up to the UpdateImage() method to react to _stopping == true and stop with what it is doing.
Your Dispose() can then use
_stopping = true;
_updateThread.Join()
Save your thread variable 't' so that you can re-use it later.
Within your Dispose method you want something like:
void IDisposable.Dispose()
{
if(t.IsRunning)
{
cancelThreads = true; // Set some cancel signal that the thread should check to determine the end
t.Join(500); // wait for the thread to tidy itself up
t.Abort(); // abort the thread if its not finished
}
base.Dispose(true);
}
You should be careful aborting threads though, ensure that you place critical section of code within regions that won't allow the thread to stop before it has finished, and catch ThreadAbortExceptions to tidy anything up if it is aborted.
You can do something like this in the threads start method
public void DoWork()
{
try
{
while(!cancelThreads)
{
// Do general work
Thread.BeginCriticalRegion();
// Do Important Work
Thread.EndCriticalRegion();
}
}
catch(ThreadAbortException)
{
// Tidy any nastiness that occured killing thread early
}
}
I suggest to override the Dispose method in your Custom Control.
There you have the reference of your thread and you can call .Join() for example...

Should Locks and Mutexes in C# be used together

Wouldn't this be overkill and only one of these necessary? I've searched and found different posts about Mutual Exclusion and locks in C# here and here.
Example:
In our app, we have a function that spins off multiple reconnection threads and inside this thread we use a Mutex and a lock. Wouldn't lock block access to this section of code and prevent connect from being updated by any other thread?
bool connect = false;
Mutex reconnectMutex = new Mutex(false, "Reconnect_" + key);
try
{
lock(site)
{
if(site.ContainsKey(key))
{
siteInfo = (SiteInfo)site[key];
if(reconnectMutex.WaitOne(100, true))
{
connect = true;
}
}
}
if (connect)
{
// Process thread logic
}
}
catch
{}
reconnectMutex.ReleaseMutex();
More Info:
This is in an ASP.NET WebService not running in a Web Garden.
That Mutex (because it has a name) will stop any process on the same machine accessing it as well, whereas lock will only stop other threads in the same process. I can't see from that code sample why you'd need both kinds of lock. It seems good practice to hold the simple lock for a short period of time - but then the much heavier interprocess mutex is locked for a probably longer (though overlapping) period! Would be simpler to just use the mutex. And perhaps to find out whether an interprocess lock is really necessary.
By the way, catch {} is absolutely the wrong thing to use in that scenario. You should use finally { /* release mutex */ }. They are very different. The catch will swallow far more kinds of exception than it should, and will also cause nested finally handlers to execute in response to low-level exceptions such as memory corruption, access violation, etc. So instead of:
try
{
// something
}
catch
{}
// cleanup
You should have:
try
{
// something
}
finally
{
// cleanup
}
And if there are specific exceptions you can recover from, you could catch them:
try
{
// something
}
catch (DatabaseConfigurationError x)
{
// tell the user to configure the database properly
}
finally
{
// cleanup
}
"lock" is basically just a syntactic sugar for Montor.Enter/Exit. Mutex is a multi-process lock.
They have very different behavior. There is nothing wrong with using both in the same application or methods, since they're designed to block different things.
However, in your case, I think you may be better off looking into Semaphore and Monitor. It doesn't sound like you need to lock across processes, so they are probably a better choice in this situation.
As others have pointed out, the Mutex locks across processes and the local lock (Monitor) locks only those threads owned by the current process. However ...
The code you showed has a pretty serious bug. It looks like you're releasing the Mutex unconditionally at the end (i.e. reconnectMutex.ReleaseMutex()), but the Mutex is only acquired if site.ContainsKey() returns true.
So if site.ContainsKey returns false, then releasing the Mutex is going to throw ApplicationException because the calling thread does not own the Mutex.
You didn't give enough info to really answer this. As already stated by Earwicker a Mutex allows you to have a synchronization accross processes. Thus if you have two instances of the same app running you can serialize access. You might do this for example when using external resources.
Now you lock on site protects site from access by other threads in the same process. This might be nessecary depending on what other methods / threads are doing. Now if this is the only place that site is being locked then yes I would think it is overkill.

Proper way to clean up a permanent thread in C#

I have an object, a Timeline, that encapsulates a thread. Events can be scheduled on the timeline; the thread will wait until it is time to execute any event, execute it, and go back to sleep (for either (a) the time it takes to get to the next event or (b) indefinitely if there are no more events).
The sleeping is handled with a WaitEventHandle, which is triggered when the list of event is altered (because the sleep delay may need to be adjusted) or when the thread should be stopped (so the thread can terminate gracefully).
The destructor calls Stop(), and I've even implemented IDisposable and Dispose() also calls Stop().
Still, when I use this component in a forms application, my application will never shut down properly when I close the form. For some reason, Stop() is never called, so neither my object's destructor triggers, nor is the Dispose() method called, before .NET decides to wait for all threads to finish.
I suppose the solution would be to explicitly call Dispose() myself on the FormClose event, but since this class is going to be in a library, and it is actually a layer deeper (that is, the application developer will never actually see the Timeline class), this seems very ugly and an extra (unnecessary) gotcha for the application developer. The using() clause, which I would normally use when resource release becomes an issue, doesn't apply as this is going to be a long-lived object.
On the one hand, I can understand that .NET will want to wait for all threads to finish before it does its final round of garbage collection, but in this case that produces a very clumsy situation.
How can I make my thread clean up after itself properly without adding requirements to consumers of my library? Put another way, how can I make .NET notify my object when the application is exiting, but before it will wait for all threads to finish?
EDIT: In response to the people saying that it is ok for the client program to be aware of the thread: I respectfully disagree.
As I said in my original post, the thread is hidden away in another object (an Animator). I instantiate an Animator for another object, and I tell it to perform animations, such as "blink this light for 800ms".
As a consumer of the Animator object, I do not care how the Animator makes sure that the light blinks for exactly 800ms. Does it start a thread? I don't care. Does it create a hidden window and use system timers (ew)? I don't care. Does it hire midgets to turn my light on and off? I don't care.
And I especially don't want to have to care that if I ever create an Animator, I have to keep track of it and call a special method when my program exits, in contrast to every other object. It should be a concern of the library implementor, not the library consumer.
EDIT: The code is actually short enough to show. I'll include it for reference, sans methods that add events to the list:
internal class Timeline : IDisposable {
private Thread eventThread;
private volatile bool active;
private SortedList<DateTime, MethodInvoker> events = new SortedList<DateTime,MethodInvoker>();
private EventWaitHandle wakeup = new EventWaitHandle(false, EventResetMode.AutoReset);
internal Timeline() {
active = true;
eventThread = new Thread(executeEvents);
eventThread.Start();
}
~Timeline() {
Dispose();
}
private DateTime NextEvent {
get {
lock(events)
return events.Keys[0];
}
}
private void executeEvents() {
while (active) {
// Process all events that are due
while (events.Count > 0 && NextEvent <= DateTime.Now) {
lock(events) {
events.Values[0]();
events.RemoveAt(0);
}
}
// Wait for the next event, or until one is scheduled
if (events.Count > 0)
wakeup.WaitOne((int)(NextEvent - DateTime.Now).TotalMilliseconds);
else
wakeup.WaitOne();
}
}
internal void Stop() {
active = false;
wakeup.Set();
}
public void Dispose() {
Stop();
}
}
Maybe set the Thread.IsBackground property to true?
eventThread = new Thread(executeEvents);
eventThread.IsBackground = true;
eventThread.Start();
Another option is to use the Interrupt method to wake it up. Just make sure that you catch the ThreadInterruptedException in the thread that you are interrupting, and that it shuts down when it happens.
active = false;
eventThread.Interrupt();
try { eventThread.Join(); } // Wait for graceful shutdown
catch (Exception) { }
Not quite sure how that EventWaitHandle of yours works though... When I did something similar once, I just used the regular Thread.Sleep =)
I don't think it is unreasonable to require clients to Stop() the thread for shutdown at all. There are ways you can create threads whose continued execution will not stop the application from exiting (although I don't have the details off the top of my head). But expecting to launch and terminate a worker thread is not too much of a burden for the client.
There is no way to get .NET to notify your thread without the clients cooperation. If you're designing your library to have a long running background thread, then the client app has to be designed to know about it.
Application::ApplicationExit is a static event, is it acceptable to listen for it and do your special cleanup work?
Implementing IDisposable should be enough indication that your clients should be using your class in a "using" block.
Implement IDisposable properly, including implementing a finaliser that calls Dispose(true). You Animator object can then do any clean up it wishes to, including stopping the thread if necessary.

Categories