简体   繁体   English

C# - 使用OnStart方法调用线程

[英]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? 我在C#中构建一个Windows服务,我有一个名为OnStart的方法,我的所有业务逻辑都在一个名为code.cs的文件中,如何告诉OnStart方法在code.cs中调用stater方法“starter” ?

/// <summary>
/// OnStart: Put startup code here
///  - Start threads, get inital 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. OnStart需要返回,以便Windows知道服务已启动。 You should launch a new Thread in OnStart that calls your starter. 您应该在OnStart中启动一个调用启动器的新线程。 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. 假设您当前的Starter方法不会产生它自己的线程。 The key is to allow OnStart to return. 关键是允许OnStart返回。

You will have to create an instance of an object and call the method on the instance. 您必须创建对象的实例并在实例上调用该方法。

Eg 例如

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. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM