Logic for Windows Services & Getting Updates - c#

I developed a Windows service using vb.net which does the following using OnStart Even...
Grabs all Entries from a SQL Table
Creates Schedules from returned rows
it works fine, schedules fire on their time and stuff.
Problem: Whenever I have to ADD a new row to my Table, I have to restart the Service, So it can Grab the Newly created rows. This is causing problems for me...there could be a task which is running already and restarting service might break the system.
So what is the best way to handle this? Can the new rows be loaded into Service without a restart?
Thanks

Use the concept of Polling into the Database. Use the System.Threading.Timer class, set some interval after which a callback method will be invoked and that will be responsible to Poll the Database for new entries.

This OnStart was provided here by Marc Gravell:
public void OnStart(string[] args) // should this be override?
{
var worker = new Thread(DoWork);
worker.Name = "MyWorker";
worker.IsBackground = false;
worker.Start();
}
void DoWork()
{
// do long-running stuff
}
Note that OnStart can launch multiple threads or the first thread started may be used to start additional threads as needed. This allows you to set up either database polling or a thread that waits on a message queue for data.
A useful tip:
Adding a Main to your service allows you to run it as a console application in Visual Studio. This greatly simplifies debugging.
static void Main(string[] args)
{
ServiceTemplate service = new ServiceTemplate();
if (Environment.UserInteractive)
{
// The application is running from a console window, perhaps creating by Visual Studio.
try
{
if (Console.WindowHeight < 10)
Console.WindowHeight = 10;
if (Console.WindowWidth < 240) // Maximum supported width.
Console.WindowWidth = 240;
}
catch (Exception)
{
// We couldn't resize the console window. So it goes.
}
service.OnStart(args);
Console.Write("Press any key to stop program: ");
Console.ReadKey();
Console.Write("\r\nInvoking OnStop() ...");
service.OnStop();
Console.Write("Press any key to exit: ");
Console.ReadKey();
}
else
{
// The application is running as a service.
// Misnomer. The following registers the services with the Service Control Manager (SCM). It doesn't run anything.
ServiceBase.Run(service);
}
}

Related

"Resource Monitor" shows me more threads than the two that I wrote on my program

I am learning about Threads. Im using C# with .NET Framework 4.5.2 and Windows 10 x64.
I wrote a simple program with two threads and one large loop in each one:
class Program
{
static void Main(string[] args)
{
Thread t = new Thread(foo);
t.Start();
for (int i = 0; i < 99999999; i++)
{
Console.WriteLine("x");
}
}
static void foo()
{
for (int i = 0; i < 99999999; i++)
{
Console.WriteLine("y");
}
}
}
And when I run the final release of the program, in "Resource Monitor" I read it is running more than two threads.
It leads me to understand that we can't have a real control of how our application will be executed, only we can say "I want to run X at the same time than Y", but no a strict (real) control of number of threads that will be created. Is that correct?
I want to know the explanation of this behaviour.
Here a image of what I've just explained:
You have at least three threads when you run your application without a debugger attached and without creating any additional thread.
Remember that the garbage collector works on a separate thread. Also the finalizer works on a separate thread. The Main Thread is Trivial in this discussion.
When you see more threads, you need to keep in mind that when debugging using Visual Studio, there are debug-related threads running.
To test that, create a simple program like the below :
class Program
{
static void Main(string[] args)
{
Console.ReadKey();
}
}
Build your application, and run it using the Executable (Without Visual Studio Debugger Attached), you would see exactly 3 threads in the resource monitor.

Unable to start multiple Processes (C#)

I am unable to successfully start multiple processes from a console application.
I have a visual studio solution with a console application A, which must start multiple instances of another console application (B).
B runs in a loop catching incoming network traffic on a port specified in the process arguments.
To simplify the problem, I have removed any network logic and made it as basic as possible, yet I still have the same problem.
Code for A, where Test.exe is console application B:
static void Main(string[] args)
{
try
{
for (int i = 0; i < 5; i++)
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo { FileName = "Test.exe" });
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
Code for B:
static void Main(string[] args)
{
int counter = 0;
while (Console.KeyAvailable == false || Console.ReadKey().Key != ConsoleKey.Escape)
{
Console.WriteLine("" + counter);
System.Threading.Thread.Sleep(1000);
counter++;
}
Console.ReadLine();
}
Once I run console application A in Visual Studio debug, A pops up as intended, but only one window of B pops up starting to count as specified. However, if I look in my task manager I can see that in fact two Test.exe is running, where one is using 116K memory and the other is using 180,000K memory.
Once the counter reaches 15, it closes and opens two new windows which both starts counting from 0. This behavior continues, opening new instances of B every time counter reaches 15 until 5 instances is running as specified in A.
Obviously this behaviour is not what I intended, I want A to launch B 5 times (in this example) immediately without waiting for the proccesses to exit.
After re-installing .net and removing certain features I no longer needed, it is finally working as intended. Starting 50 instances is no problem and the weird memory usage is no longer evident.
The culprit was either Windows Phone SDK or Windows Azure for VS.

How can a Windows Service create a process?

I want to create program that run all the time (not a Windows Service exactly). I want it to have no view to the user.
I would like it to be a process, the reason I don't want it to be service is because I want to create to process and I want one service to start them.
I don't know how to create the program without any UI as if I create console application the CMD open when I run the program.
I'm taking a guess as to what you're trying to do, but here's a really simple console application that runs until you hit the ENTER key. It will print out a line to the console every second.
class Program
{
static void Main(string[] args)
{
using (System.Threading.Timer processTimer = new System.Threading.Timer(DoSomething, "fun", 0, 1000))
{
Console.ReadLine();
}
}
static void DoSomething(object data)
{
Console.WriteLine("doing something {0}...", data.ToString());
}
}
You can replace the contents of DoSomething with what you need your console runner to do.
I hope this helps.

Checking if a console application is still running using the Process class

I'm making an application that will monitor the state of another process and restart it when it stops responding, exits, or throws an error.
However, I'm having trouble to make it reliably check if the process (Being a C++ Console window) has stopped responding.
My code looks like this:
public void monitorserver()
{
while (true)
{
server.StartInfo = new ProcessStartInfo(textbox_srcdsexe.Text, startstring);
server.Start();
log("server started");
log("Monitor started.");
while (server.Responding)
{
if (server.HasExited)
{
log("server exitted, Restarting.");
break;
}
log("server is running: " + server.Responding.ToString());
Thread.Sleep(1000);
}
log("Server stopped responding, terminating..");
try
{ server.Kill(); }
catch (Exception) { }
}
}
The application I'm monitoring is Valve's Source Dedicated Server, running Garry's Mod, and I'm over stressing the physics engine to simulate it stopping responding.
However, this never triggers the process class recognizing it as 'stopped responding'.
I know there are ways to directly query the source server using their own protocol, but i'd like to keep it simple and universal (So that i can maybe use it for different applications in the future).
Any help appreciated
The Responding property indicates whether the process is running a Windows message loop which isn't hung.
As the documentation states,
If the process does not have a MainWindowHandle, this property returns true.
It is not possible to check whether an arbitrary process is doing an arbitrary thing, as you're trying to.

C# service fails to start

I have created a C# Windows service but it fails to start. I get the following message when I attempt to start it:
The System Usage Monitor service on Local Computer started and then stopped. Some services stop automatically if they have no work to do, for example, the Performance Logs and Alerts service.
The following is my OnStart override ...
/// <summary>
/// OnStart(): Put startup code here
/// - Start threads, get inital data, etc.
/// </summary>
protected override void OnStart(string[] args)
{
base.OnStart(args);
broadcaster = new UdpBroadcaster(IP_Address, Port);
itm = new IdleTimeMonitor(1 * 1 * 3000, 1000);
aam = new ActiveApplicationMonitor(1000);
itm.IdleTimeExceeded += new IdleTimeExceededDelegate(itm_IdleTimeExceeded);
itm.IdleTimeReset += new IdleTimeResetDelegate(itm_IdleTimeReset);
itm.IdleTimeEvaluated += new IdleTimeEvaluatedDelegate(itm_IdleTimeEvaluated);
aam.StartedUsingApplication += new StartedUsingApplicationDelegate(aam_StartedUsingApplication);
aam.EndedUsingApplication += new EndedUsingApplicationDelegate(aam_EndedUsingApplication);
aam.ApplicationEvaluated += new ApplicationEvaluatedDelegate(aam_ApplicationEvaluated);
}
Do I need to block at the end of that function or something? Why wont my service start?
Did you kick off a thread?
If you don't have a thread that does something then the application will close so when onstart finishes there is no thread (unless you kick one off in UdpBrodacaster) so the service closes.
EDIT: Just declare a ManualResetEvent that isn't signalled and have the thread call WaitOne() on it. Then in your OnStop() signal the event (.Set()) to have the thread wake up and exit thus closing your service.
Take a look in the event log, if your service is starting then crashing for some reason there will be an exception event in the Application Log.
Put your code in the OnStart(string[]) in a try-catch-Block and log the exception to a log file (if one is raised). I think there is a problem on creating the instances.

Categories

Resources