Application is not qutting from task manager - c#

I have an application running with the thread,if i perform end-task from the task manager
application is quitting but,in process list an instance will be running(i.e if I do end-task 5 times 5 instances of process running). It might be due to thread.
in this case,if I have to kill all process i need to restart the device :-(.
Manually if I exit It works great.How to overcome from this issue?
I am developing application in c#

As elder_george points out, you have a rogue thread that is preventing the app from exiting and you need to ensure that thread exits when your app shuts down. With CF 3.5 you can usually just set the IsBackground property to truw, though that's not always enough. If the thread is blocking in a system call (like an infinite wait like WaitOne) then the thread will not get schedules and still may not terminate.
The best way to prevent this, and a good practice, is to actually write code that signals your worker threads to shut themselves down. This is often done with a reset event or a boolean flag that the thread checks periodically.
void MyThreadProc()
{
// set this event when the app is shutting down
while(!shutdownEvet.WaitOne(0, false))
{
// do my thread stuff
}
}
This mechanism will also work in CF 2.0 (where IsBackground doesn't exist).

Set IsBackground property on your thread to true.

Hey i got solution for this,
when i perform end task from task manager,control will come next to "Application.Run()" method.
There we can call one user defined function, in that we can perform all the necessary task like killing thread, memory clean up etc.. to end the application smoothly.
Thanks to all for your responses.

Related

Does a Task end if you close the application?

So, I basically have this:
public void DoThisThing()
{
Task.Run(() =>
{
while(true)
{
//Do things
}
}
}
The start of the application basically calls the DoThisThing() method and enters it's own loop.
So, if I just close the application, what happens to this task? Does it just end? does it continue forever? Does it go on for a little bit until garbage collection gets it? Does it have a way to know the application ended?
I googled, but I couldn't get a simple answer, and I feel like there definitely is one.
The first question is, how this task is even executed. According to the Documentation:
Queues the specified work to run on the ThreadPool and returns a task or Task handle for that work.
Each programm starts with one Thread, but can start further. This one is the Main Thread, the GUI Thread and a few other names. As a general rule, if that main thread is ending, all others threads it started are canceled too. This is a OS level rule, to avoid Zombie Threads with infinite loops running all over the place.
The ThreadPool and all it's data - including sheduled and running Threads - will be collected by the "End of Application" Garbage Colleciton. If not, there is propably some OS features to make sure they end as well. But I prefer not to mention those OS fallbacks, as we really should not be using them ever. There are for cases when even the GC can no longe run properly (like Programm being killed via Task Manager).
One of the big challenges of Multitasking and -threading is keeping the main Thread alive, but without blocking it so further I/O can happen. In a GUI you have that work done for you (with the EventQueue).
All which is said below is implementation details - FOR WINDOWS - and mostly undocumented behavior. Do not rely on any of the information.
As an implementation detail, this task will most likely be scheduled to execute on a thread pool thread.
If the task has not started by the time the process exit starts, it won't matter it was queued in the first place.
If the task is currently executing, then according to some of the implementation details of process shutdown on Windows eventually only one thread will be executing which will not be the one executing this task. So, it will be forcibly terminated in that case.
If the task has already finished execution, whether through completion or by throwing an exception then there's no thread occupied by it. However, if the exception was left unobserved then the finalizer - should it get a chance to execute - will throw that. Please note that finalizers are also not guaranteed to execute under any circumstances.
This page should have been visible, but Microsoft's latest screw up in revoking access to old MSDN blogs continues.
Similarly, if you can manage to track the first link on this page then do so and read it.
P.S.: Here's the link for Raymond's blog. What you'll find from both sources is that only one thread continues the process shutdown.
The answer depends on the content of the while loop.
If the loop is running some logic that runs entirely within the scope and control of the main program, then closing the application will terminate everything.
However, if the loop is calling some external routines or operating system functions (Example: write to a file, open a network connection, run a command, start a batch job, etc), then closing the application will not terminate everything.
Based on your sample, in brief: Yes
Tasks that are created by TPL (using Task.Run or Task.Factory.StartNew) by default are background threads. So closing application will immediately terminate them.
This post could be helpfull.

Does Sleep block program exit? How is it implemented?

In a single-threaded console application, people often use Thread.Sleep as a lazy way to pause the application for some time.
This question raised interesting points about NOT using this approach: Why is Thread.Sleep so harmful
However other than knowing that Sleep blocks the current thread, I don't understand how it works - for instance does it max out the CPU core in a tight loop or does it actually pause the thread?
More importantly to me, how does a console app respond to various app-exit scenarios (CTRL-C, kill, window close button) when caught in the middle of a Sleep? Will it blindly continue executing until the OS force-kills it, or will it behave well?
This is more of an OS question than a C#/.NET related question, but I'll try and answer succinctly.
Thread.Sleep will not spin lock your CPU, instead it will call the appropriate mechanism in the underlying OS to suspend your thread. On windows, that function is described here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms686298(v=vs.85).aspx
Using this normal system call your thread cannot be rescheduled until the timeout has elapsed. Forcefully killing the thread (or the entire process) is then required.
When you hit ctrl+c in cmd.exe, the console spawns a new thread in each process attached to handle the event (Described here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms682541(v=vs.85).aspx). Because of this, your program as a whole will still "behave well" when you hit ctrl+c, but your sleeping thread itself will wind up being killed prematurely.
This is source code of Thread.Sleep method:
[System.Security.SecuritySafeCritical] // auto-generated
public static void Sleep(int millisecondsTimeout)
{
SleepInternal(millisecondsTimeout);
// Ensure we don't return to app code when the pause is underway
if(AppDomainPauseManager.IsPaused)
AppDomainPauseManager.ResumeEvent.WaitOneWithoutFAS();
}
As we can see this method calls Thread.SleepInternal method. In comment about it we can read that this method suspends the current thread for timeout milliseconds. Next, we can read that if timeout == 0 then this method forces the thread to give up the remainder of its timeslice and if timeout equals Timeout.Infinite then no timeout will occur. I recommend you reading about multithreading and application lifecycle (in this case especially suspended).
Links:
https://msdn.microsoft.com/en-us/library/ms900951.aspx
https://msdn.microsoft.com/en-us/windows/uwp/launch-resume/app-lifecycle

Application_End and background processes, exiting ASP.Net application gracefully

I have an ASP.Net application which fires off some background workers using ThreadPool.QueueUserWorkItem(). Most of the time there will be zero background threads running, however it's possible that there could occationally be up to 5-6 executing at a time. Additionally, most will complete within a couple seconds, but it is possible that they could run for as long as 10 minutes.
Given all the different scenarios that could cause a shutdown of an ASP.Net application, I'd like to have these background processes exit gracefully if possible when the application needs to shutdown and they are in the middle of processing.
I don't anticipate having too much of an issue creating a way to signal the processes to stop their work early and clean up within a few seconds of getting the call that the application is being shut down. Although if anyone has specific advice on this I'd certainly appreciate it.
My two main questions are:
1) When would be the appropriate time to tell the background workers to wrap things up. During Application_End? Dispose()? Or perhaps a third option I'm not aware of.
2) If I wait during the above event for the processes to finish before returning, is there a point where not having Application_End return immediately could cause more serious issues for the application than not shutting down the background jobs nicely.
void Application_End(object sender, EventArgs e)
{
//if this for whatever reason takes a non-trivial time to execute, what problems could I encounter?
SignalBackgroundJobsAndWaitForThemToShutDown();
}
Thanks!
The appropriate time is on the Application_End
Now after you signal your background jobs you must wait for them at that point to end, and then let continue, as its seems that you do.
Have in mine, that is good to place a time out on the wait, not wait for ever or else your pool may have problems, or shutdown, then you need to check your pool setting on the max wait to shutdown the pool, there set a value larger than your wait, or just disabled it.
Also have in mine that if you have pool garden, (more than 1 working pools) then the Application_End is called one time for each pool.
I use the same technique on my sites, the same way I signal my threads to stop the same way, I just also log the final end, and check when they are final end, and also I force my routines to stop and not let them run for many time. The Application_End is called on recycle the pool, or when you open the app_offline.htm file, or when you go to close the web service. Personally I have disable the recycles, I do not need them and I only open the app_offline.htm when I make updates. At that moment I wait my pool threads to stop their work.

Most appropriate thing to do with Main() method for long running async processes

I have a basic C# console application that executes a fairly long running process involving timers and asynchronous requests. The sole purpose of the Main() method is to initialize the timers and then let them do their thing for the next few hours.
I know that Windows Services are appropriate for many long running processes, but doesn't feel appropriate for this use case (executed manually when needed, always terminated within a day, no hurdles of having to install the Service, etc).
Right now, I simply do:
while (true)
Thread.Sleep(5000);
Throwing in a Thread.Sleep seems ... dirty for some reason. Or is that really the best thing to do to stop the application from terminating before the async process are complete?
You could use one/multiple ManualResetEvent to communicate from the background threads to the foreground thread.
The foreground thread in Main could wait until all background threads signaled that they are finished.
You shouldn't be Thread.Sleep, but isntead you should be waiting on some sort of event that would get signaled when there is anything to do, including shuting yourself down.
The application you describe though would much better fit as a service, not as a console app.

C# Communication between threads

I am using .NET 3.5 and am trying to wrap my head around a problem (not being a supreme threading expert bear with me).
I have a windows service which has a very intensive process that is always running, I have put this process onto a separate thread so that the main thread of my service can handle operational tasks - i.e., service audit cycles, handling configuration changes, etc, etc.
I'm starting the thread via the typical ThreadStart to a method which kicks the process off - call it workerthread.
On this workerthread I am sending data to another server, as is expected the server reboots every now and again and connection is lost and I need to re-establish the connection (I am notified by the lost of connection via an event). From here I do my reconnect logic and I am back in and running, however what I easily started to notice to happen was that I was creating this worker thread over and over again each time (not what I want).
Now I could kill the workerthread when I lose the connection and start a new one but this seems like a waste of resources.
What I really want to do, is marshal the call (i.e., my thread start method) back to the thread that is still in memory although not doing anything.
Please post any examples or docs you have that would be of use.
Thanks.
You should avoid killing the worker thread. When you forcibly kill a Win32 thread, not all of its resources are fully recovered. I believe the reserved virtual address space (or is it the root page?) for the thread stack is not recovered when a Win32 thread is killed. It may not be much, but in a long-running server service process, it will add up over time and eventually bring down your service.
If the thread is allowed to exit its threadproc to terminate normally, all the resources are recovered.
If the background thread will be running continuously (not sleeping), you could just use a global boolean flag to communicate state between the main thread and the background thread. As long as the background thread checks this global flag periodically. If the flag is set, the thread can shut itself down cleanly and exit. No need for locking semantics if the main thread is the only writer and the background thread only reads the flag value.
When the background thread loses the connection to the server that it's sending data to, why doesn't it perform the reconnect on its own? It's not clear to me why the main thread needs to tear down the background thread to start another.
You can use the Singleton pattern. In your case, make the connection a static object. Both threads can access the object, which means construct it and use it.
The main thread could construct it whenever required, and the worker thread access it whenever it is available.
Call the method using ThreadPool.QueueUserWorkItem instead. This method grabs a thread from the thread pool and kicks off a method. It appears to be ideal for the task of starting a method on another thread.
Also, when you say "typical ThreadStart" do you mean you're creating and starting a new Thread with a ThreadStart parameter, or you're creating a ThreadStart and calling Invoke on it?
Have you considered a BackgroundWorker?
From what I understand, you just have a single thread that's doing work, unless the need arises where you have to cancel it's processing.
I would kill (but end gracefully if possible) the worker thread anyway. Everything gets garbage-collected, and you can start from scratch.
How often does this server reboot happen? If it happens often enough for resources to be a problem, it's probably happening too often.
The BackgroundWorker is a bit slower than using plain threads, but it has the option of supporting the CancelAsync method.
Basically, BackgroundWorker is a wrapper around a worker thread with some extra options and events.
The CancelAsync method only works when WorkerSupportsCancellation is set.
When CancelAsync is called, CancellationPending is set.
The worker thread should periodically check CancellationPending to see if needs to quit prematurely.
--jeroen

Categories