4

I've created a windows service that creates a Form in which a tool strip icon is created to manage a socket. I'm able to install through an installer created in Visual Studio, but when I go to Services and start my service it gives me an error saying it started and stopped immediately.

Here's the service code:

public Service()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        base.OnStart(args);

        ServiceName = "WizardServer";
        CanPauseAndContinue = false;
        CanHandleSessionChangeEvent = true;
        CanStop = true;

        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        try
        {
            connectionHandler = new ConnectionHandler();  
            serviceThread = new System.Threading.Thread(new ThreadStart(serviceTarget));
            alive = true;
            serviceThread.Start();
        }
        catch {}
    }

    private void serviceTarget()
    {
        Application.Run(new Form1(connectionHandler));

        while (alive) 
        {
            Thread.Sleep(10000);
        }
    }

    protected override void OnStop()
    {
        base.OnStop();

        try
        {
            connectionHandler.stop();
        }
        catch {}

        serviceThread.Abort();

        alive = false;
        Stop();
    }

PS: I've tested the form and it works just fine.

4

2 回答 2

1

我遇到了这个问题,在谷歌上搜索了好几个小时,然后我找到了解决方案。您可以在代码中添加以下代码。添加InitializeTimer()你的类构造函数。你应该 SetoTimer.Enabled = trueoTimer.Start()onOnStart()oTimer.Stop()on OnStop()

代码:

  void create()
    {
        string s = "";
    }
    void InitializeTimer()
    {
        oTimer = new System.Timers.Timer(interval);
        oTimer.AutoReset = true;
        oTimer.Enabled = true;
        oTimer.Elapsed += new System.Timers.ElapsedEventHandler(oTimer_Elapsed);
    }

    void oTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        CreateFileData();
    }

    void CreateFileData()
    {
        string path = @"C:\SimpleWcfService\SimpleWindowsService\bin\Release\Singh.txt";
        StreamWriter oStreamWriter = new StreamWriter(path, true);
        oStreamWriter.WriteLine(DateTime.Now.ToString());
        oStreamWriter.Close();
        oStreamWriter = null;
    }
于 2014-08-30T07:33:27.150 回答
0

我回答这个问题的时间太晚了,但希望这会帮助其他遇到同样问题的人:

更改 Windows 服务项目属性中的“输出类型”为我修复了它。

  1. 在解决方案资源管理器中,找到您的项目并双击“属性”
  2. 在打开的窗口中,转到“应用程序”选项卡
  3. 将“输出类型”下的值更改为“控制台应用程序”
于 2019-03-05T15:44:08.440 回答