Solved

windows services - the onstart method

Posted on 2010-08-23
7
1,432 Views
Last Modified: 2013-12-04


I am setting up a windows service...curious on the OnStart method...how do I launcha particular function inside my asp.net and/or vb.net

Its important that I launch this function as it kicks off a process...

---


Also, how do I know if I need to add installers to the service?



Public Class MyNewService

    Protected Overrides Sub OnStart(ByVal args() As String)
        ' Add code here to start your service. This method should set things
        ' in motion so your service can do its work.

        EventLog1.WriteEntry("In OnStart")

    End Sub

    Protected Overrides Sub OnStop()
        ' Add code here to perform any tear-down necessary to stop your service.
    End Sub

End Class
0
Comment
Question by:GlobaLevel
  • 5
  • 2
7 Comments
 
LVL 3

Expert Comment

by:arthurmnev
ID: 33505566
Launch a function in a separate thread.

In your code you'd declare a thread variable, assign a delegate to it, and start it.
When the stop event is signaled, you need to have the thread terminate

- check on mutex, semaphore and manual reset event objects for cross thread synchronization;
- look at Interlocked function sets for variable management.
- consider using volatile variables to ensure you don't have an opportunity to work with stale / invalid data.


0
 
LVL 3

Expert Comment

by:arthurmnev
ID: 33505579
In reference to installers -- you do want to add those to the final project . The installers will greatly simplify your life during service installation.  Once you get the mechanics of a separate / worker thread , -- you can develop and test everything in IDE without compiling and installing the service, then just "plug" your code in.
0
 
LVL 10

Author Comment

by:GlobaLevel
ID: 33505610
any samples ..kinda new at creating a service...

once a setup is created...any way to deploy on various clients with customization..or manual setup...just wanted to drop the service on the clients and go...
0
NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

 
LVL 3

Expert Comment

by:arthurmnev
ID: 33505615
To start a job in ASP.NET , you can use web services for dimpliest implementation of IPC . Essentially , your web service will make a SOAP call to a web server / web service. Since web service translates more or less into execution of a function -- once started , you can do what you need in there.
0
 
LVL 3

Expert Comment

by:arthurmnev
ID: 33505688
I'll try to put a sample together.

In your mind though, you need to separate the "Service" from "the application"; the service, (oversimplifying) is the same as your "Application.Run" clause for winforms. It anchors the process and prevents it from exiting. When winforms app calls Application.Run, it spawns a window that anchors your runtime. The OnStart service call, does the same, the only thing you are missing is the function that it calls (whereas Application.Run calls CreateWindow)
0
 
LVL 3

Accepted Solution

by:
arthurmnev earned 500 total points
ID: 33506145
I cant write normal VB code, it has been a while since I did any VB work, here is some C# , you should be able to read it though -- it is very simple:


The major elements there is the worker thread that gets created during on start event
the thread executes a worker function
the worker function loops while continue working evaluates to true
on every loop it generates a random name and creates a file with that random name , writes 5 bytes into the file and closes it
sleeps for 10 seconds
goes on the next loop

OnStop event , changes the value of the volatile variable, on the next loop, the worker thread will evaluate the value to false and exit once the loop has been completed.

Obviously, the worker thread should have error handling (try / catch / on error etc...) it should NEVER exit without service control signal.



       System.Threading.Thread workerthread = null;
        volatile bool ContinueWorking = true;


        protected override void OnStart(string[] args)
        {
            ContinueWorking = true;
            workerthread = new System.Threading.Thread(new System.Threading.ThreadStart(WorkerT));
            workerthread.Start();
            this.EventLog.WriteEntry("event message text", EventLogEntryType.Information);
            base.OnStart(args);

        }
        protected override void OnStop()
        {
            ContinueWorking = false;
            // give the worker 30 seconds to finish, abort after
            workerthread.Join(30000);
            if (workerthread.ThreadState != System.Threading.ThreadState.Stopped)             workerthread.Abort();

            base.OnStop();
        }

        private void WorkerT()
        {
            // go into endless loop, the only way to leave this loop is through a signal
            while (ContinueWorking)
            {
                string fFileName = Guid.NewGuid().ToString();
                System.IO.FileStream fs = new System.IO.FileStream(@"c:\" + fFileName + ".txt", System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None, 2048);
                fs.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5);
                fs.Flush();
                fs.Close();
                System.Threading.Thread.Sleep(10000);
            }
            string fexit = Guid.NewGuid().ToString();
            System.IO.FileStream fe = new System.IO.FileStream(@"c:\exit_" + fexit + ".txt", System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite, System.IO.FileShare.None, 2048);
            fe.Write(new byte[] { 1, 2, 3, 4, 5 }, 0, 5);
            fe.Flush();
            fe.Close();

        }

Open in new window

0
 
LVL 10

Author Comment

by:GlobaLevel
ID: 33532912
Thanks a few questions ... Doesn't the express offer windows services?

I am writing my Asp.net code to automatically created vb. Net apps on the client that need to listen to the server... These vb.net apps will be customized based on client, do I need to programmatically create custom window services for each custom vbnet app or can I use the same windows service on each client install?  I'm Turing to make the install for window services on the client as easy as possible for the user thaks
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The use of stolen credentials is a hot commodity this year allowing threat actors to move laterally within the network in order to avoid breach detection.
Join Greg Farro and Ethan Banks from Packet Pushers (http://packetpushers.net/podcast/podcasts/pq-show-93-smart-network-monitoring-paessler-sponsored/) and Greg Ross from Paessler (https://www.paessler.com/prtg) for a discussion about smart network …
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

685 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question