Process Service Thread - multithreading

We know about relation between Process and Thread.
Thread comes under Process, we can say Process is a container and Thread is an element of a container.
But what about Service ?
I can say Process and Thread having same genre.
Can we say the same thing for Services?
I found Window Services and Android Services having similarity, say in Android if we want to play Media then we have to get getSystemService(Context.AUDIO_SERVICE) likewise in Windows (8) if you stop Windows Audio (audiosrv.dll) services from services.msc then Media will not play.
What is Service?
Windows
A service is an application type that runs in the system background without a user interface and is similar to a UNIX daemon process.
Android A service is a component which runs in the background, without direct interaction with the user.
A service runs by default in the same process in the main thread as the application.
Services which run in the process of the application are sometimes called local services.
With above definition we can say apparently that Service is also a Process (i am not sure, please make me correct)

Let me start with the statement - Service is not a process. It is an activity without GUI
If you start a thread, it runs parallel with your main activity thread. But a Service is not guaranteed to always run in a new thread. So, you cannot call a service similar to Thread.
A Service is not a separate process. The Service object itself does not imply it is running in its own process; unless otherwise specified, it runs in the same process as the application it is part of.
A Service is not a thread. It is not a means itself to do work off of the main thread (to avoid Application Not Responding errors).
So When to use of a service in your application ?
If your application tells the system about something it wants to be doing in the background (even when the user is not directly interacting with the application). This corresponds to calls to Context.startService(), which ask the system to schedule work for the service, to be run until the service or someone else explicitly stop it.
Reason - Your application together with all its global variables will not be wiped out as long as there is a Service still running. So if the user is not interacting with your application and some other application in foreground needs more memory and if the OS triggers a low memory warning and your activity is destroyed, still your application is not completely lost as the service is running.
A facility for an application to expose some of its functionality to other applications. This corresponds to calls to Context.bindService(), which allows a long-standing connection to be made to the service in order to interact with it.
How the Application priority is defined based on service ?
If the service is currently executing code in its onCreate(), onStartCommand(), or onDestroy() methods, then the hosting process will be a foreground process to ensure this code can execute without being killed.
If the service has been started, then its hosting process is considered to be less important than any processes that are currently visible to the user on-screen, but more important than any process not visible.
If there are clients bound to the service, then the service's hosting process is never less important than the most important client.
A started service can use the startForeground(int, Notification) API to put the service in a foreground state, where the system considers it to be something the user is actively aware of and thus not a candidate for killing when low on memory.

Related

Can Azure Worker Process stop itself?

Is there a way to stop the worker process by itself? I already coded in console application, which uses REST API to start and stop worker process and delete cloud service deployment. In the latest announcement, stopping worker processes will not cost anything, it is free now.
Can I make the worker process to stop itself? Is there any event in the worker process to stop itself? Please let me know.
So I think you're referring to Worker Roles, right? A worker process would simply be something you run in your app (like a thread, a method, something). Azure Worker Roles are full VMs.
Assuming that's what you meant: The new announcement about stopping VMs does not apply to Web / Worker Role instances; it applies to Virtual Machines. And those can be stopped easily via REST call (or much easier via PowerShell that wraps the REST call). You could make that call from a Virtual Machine, which would effectively shut itself down, but I'm not so sure that's a sound idea. If you take that approach, it will be very hard for you to track the role-stop progress, since you would have just stopped the VM that made the call.

Azure Development - How to stop a Web Role instance

I need to test how my code will handle the failure of a web role instance in a development environment.
How do I terminate one of the instances? I can't see any option in the UI for this. Seems like a strange ommission
Update
The issue is relating to a distributed cache layer (I know that azure offers their own)
I want to be able to test how the system reacts to a missing or additional node etc
Prehaps my real question is
how up to date is RoleEnvironment.CurrentRoleInstance.Role.Instances
The need to simulate ungraceful exits in the dev emulator usually is done because you are doing something in your web role that is stateful or long running. That is generally discouraged, but sometimes is unavoidable.
I suspect the best way to simulate the a failure is to kill processes. If you open task manager (or better Process Explorer), you will see "WatDebugger" hosting either "WaIISHost" or "WaWorkerHost". If you kill this process, I think it will simulate a failure.
Honestly, it is easier to test this one in the cloud however. You can RDP into one of the instances and kill the 'WaAppAgent' process. That will kill your RoleEntryPoint and fabric controller agent. That will be a true ungraceful failure.
By failure, do you mean becoming unavailable? It should be seamless because the next request would simply be handled by one of the other instances. As long as there is one instance available Azure will route calls to that instance.
This is the nature of a high-available system, requests are handled by the available instances. This is why you have multiple instances in the first place, to handle requests in the case of failure in one or more instances.
This is why you need to always be watchful of how your application handles state. State needs to be maintained outside of the instance, either in queues or in a database. This ensures that any process can pickup a piece of work and execute against it.
There is another question dealing with Session State that should help: How does Microsoft Azure handle Session State?
By terminate an instance do you mean reducing instance count and see which one gets killed? I like Ryan's view about ungraceful exits, but if it's forced kill by the fabric it'll be a different ball game.

What's the concept of *worker role* in Windows Azure cloud?

As I understood, it's long running process in server. Can it cover long-running program instance like online game server?
You can think of a worker role as a Windows Service or a Unix Daemon. It is, as you say, a perpetually executing process (although it may be in a wait state for a large portion of the time, but that's for you to decide).
Essentially it can run any code you'd like to write.
It can react to outside stimuli e.g. by polling from the Azure Queue service, but can also open communication channels, query databases, etc.

which one to use windows services or threading

We are having a web application build using asp.net 3.5 & SQL server as database which is quite big and used by around 300 super users for managing around 5000 staffs.
Now we are implementing SMS functionality into the application which means the users will be able to send and receive SMS. Every two minute the SMS server of the third party is pinged to check whether there are any new messages. Also SMS are hold in queue and send every time interval of 15 to 30 minutes.
I want this checking and sending process to run in the background of the application all the time, even if the user closes the browser window.
I need some advice on how do I do this?
Will using thread will achieve this or do I need to create a windows service for it or are there any other options?
More information:
I want to execute a task in a timer, what will happen if I close the browser window, the task wont be completed isn't it so.
For example I am saving 10 records to the database in a time interval of 5 minutes, which means every 5 minutes when the timer tick event fires, a record is inserted into the database.
How do I run this task if I close the browser window?
I tried looking at windows service but how do I pass a generic collection of data to it for processing.
There really is no thread or service choice, a service can (and usually is!) multi threaded, a thread can start a service.
There are three basic choices you can:-
Somehow start another thread running when a user logs in -- this is probably a very poor choice for what you want, as you cannot really keep it running once the user session is lost.
Write a fully fledged windows service which is starts on OS startup and continues running unitl the server is shutdown. You can make this dependant on the SQLserver service, so it starts after the DB is available. This is the "best" solution but may be overkill for your purposes. Aslo you need to know the services API to write it properly as you need to respond correctly to shutdown and status requests.
You can schedule your task periodically using either the Windows schedular, or, preferably the schedular which is built in to SQLServer, I think this would be the most suitable option for your needs.
Distinguish between what the browser is doing and what's happening server-side.
Your Web App is sitting server-side waiting for requests from whatever browsers may be running, and servicing those requests, in servicing those requests I guess it may well put messages on a queue and have a look in a database for any new messages.
You want the daemon processor, which talks to the third-party SMS, to be triggered by time rather than by browser function. Either of your suggestions would work:
A competely independent service could run and work against the queues and database.
Your web app, which I assume is already a service, could spawn a thread
In either case we have a few technical questions of avoiding any race conditions between the browser-request processing and the daemon - but databases and queueing systems can deal with that.
So I would decide between stand-alone daemon and background thread like this:
Which is easier to implement? I'm a Java EE developer, I know in my app server I have an API for specifying code to be run according to a timer, the API deals with the threading issues. So for me that's very easy. I don't know what you have available. Timers are not quite as trivial as they may appear - so having a reliable API is beneficial. If this was a more complex requirement, where the daemon code were gnarly and might possibly interfere with the WebApp code then I might prefer to keep it conspicuously separate.
Which is easier to deploy and administer? Deploy separate Web App and daemon, or deploy one thing. In the Java EE world we could have a single Enterprise Application with all the code, so that's a single thing to deploy, start and control.
One other thing to consider: Scaling and Resilience. You might choose to have more than one copy of your web app running, either to provide fail-over capabilities or just because you need the extra power. In which case how many daemons would you have? Would it be a problem to have two daemons running? You might need some extra code to mediate between two daemons, for example log in the database the time of last work, each daemon can say "Oh, my buddy balready did the 10:30 job, I'll go back to sleep"

How do you monitor another application until it closes?

Suppose there are two executables. One is mine and the other is some other application. Now if the other app is running, I want my app to run until the other one exits or is stopped.
Writing a separate service seems quite an overkill.
You can first obtain a Process object - say by Process.GetProcessesByName, or better - use the ProcessID of the process you wish to monitor, if you have it. You can then try obtaining a WaitHandle from it, as discussed e.g. here, then call WaitOne on it (or WaitAll, if you're monitoring several instances).
Write a windows service that will continuously monitor the other application executable. If the service finds it running it will start your executable if not running and make sure it keeps running throughout the life cycle of the other application. As soon as the other app terminates, your windows service will also terminate your exe.

Resources