Solved

windows services - the onstart method

Posted on 2010-08-23
7
1,423 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
Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

 
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
firewall inside of network 9 73
ACS vs NAC 2 72
antivirus on mac 8 74
Server 2008-R2 lost password 19 97
OfficeMate Freezes on login or does not load after login credentials are input.
David Varnum recently wrote up his impressions of PRTG, based on a presentation by my colleague Christian at Tech Field Day at VMworld in Barcelona. Thanks David, for your detailed and honest evaluation!
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
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…

867 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

Need Help in Real-Time?

Connect with top rated Experts

26 Experts available now in Live!

Get 1:1 Help Now