C# - Using the OnStart method to call a thread
I am building a Windows Service in C#, and I have a method called OnStart, all of my bussiness logic is in a file named code.cs, how can I tell the OnStart method to call the stater method "starter" in code.cs?
/// <summary>
/// OnStart: Put startup code here
/// - Start threads, get init开发者_如何学Goal data, etc.
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
base.OnStart(args);
}
OnStart needs to return in order for Windows to know the service is started. You should launch a new Thread in OnStart that calls your starter. Something like:
protected override void OnStart(string[] args)
{
Thread MyThread = new Thread(new ThreadStart(MyThreadStarter));
MyThread.Start();
base.OnStart(args);
}
private void MyThreadStarter()
{
MyClass obj = new MyClass();
obj.Starter();
}
This assumes your current Starter method does not spawn it's own thread. The key is to allow OnStart to return.
You will have to create an instance of an object and call the method on the instance.
E.g.
CodeMyClass obj = new CodeMyClass();
obj.Starter();
//Replace CodeMyClass with the Type name. or if it is a single call the appropriate constructor.
Hope this helps.
精彩评论