Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

windows services - the onstart method

Posted on 2010-08-23
7
Medium Priority
?
1,458 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Get free NFR key for Veeam Availability Suite 9.5

Veeam is happy to provide a free NFR license (1 year, 2 sockets) to all certified IT Pros. The license allows for the non-production use of Veeam Availability Suite v9.5 in your home lab, without any feature limitations. It works for both VMware and Hyper-V environments

 
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 2000 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

Will your db performance match your db growth?

In Percona’s white paper “Performance at Scale: Keeping Your Database on Its Toes,” we take a high-level approach to what you need to think about when planning for database scalability.

Question has a verified solution.

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

Article by: btan
The intent is not to repeat what many has know about Ransomware but more to join its dots of what is it, who are the victims, why it exists, when and how we respond on infection. Lastly, sum up in a glance to share such information with more to help…
In this article, WatchGuard's Director of Security Strategy and Research Teri Radichel, takes a look at insider threats, the risk they can pose to your organization, and the best ways to defend against them.
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
Suggested Courses

661 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