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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6455966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 17:09:18  来源:igfitidea点击:

C# - Using the OnStart method to call a thread

c#.netwindows

提问by Thomas

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 中的状态器方法“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);
}

采纳答案by Jemes

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:

OnStart 需要返回以便 Windows 知道服务已启动。您应该在 OnStart 中启动一个新线程来调用您的启动器。就像是:

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.

这假设您当前的 Starter 方法不会产生它自己的线程。关键是让 OnStart 返回。

回答by softwaredeveloper

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.

希望这可以帮助。