0

これは私が書いている最初のウィンドウサービスです。それを書くのに助けが必要です。一方のスレッドがサービスを開始し、もう一方のスレッドがデータベースの動作を行う関数の呼び出しを処理できるように、シングルスレッドを使用しようとしています。 。私はタイマーも使用しているので、このサービスは1日1回だけ実行されます。これが私のコードです

この質問を投稿する理由は、このサービスをインストールしようとすると、「致命的なエラーが発生しました」というエラーがスローされ、詳細が表示されないためです。

public partial class Service1 : ServiceBase
    {
        private DateTime _lastRun = DateTime.Now;
        Thread workerThread;

    public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {

            ThreadStart st = new ThreadStart(WorkerFunction);
            workerThread = new Thread(st);
            serviceStarted = true;
            workerThread.Start();
        }
     protected override void OnStop()
        {
            // flag to tell the worker process to stop
            serviceStarted = false;

            // give it a little time to finish any pending work
            workerThread.Join(new TimeSpan(0, 2, 0));
            timer1.Enabled = false;
        }

     private void WorkerFunction()
        {
                while (serviceStarted)
                {

                  EventLog.WriteEntry("Service working",
                     System.Diagnostics.EventLogEntryType.Information);

                  // yield
                  if (serviceStarted)
                  {
                     Thread.Sleep(new TimeSpan(0, 20000, 0));
                  }
                  timer1.Enabled = true;
                  timer1.Start();
                }

               // time to end the thread
               Thread.CurrentThread.Abort();
        }


         private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
            {
                    if (_lastRun.Date < DateTime.Now.Date)
                    {
                        timer1.Stop();
                // does the actual work that deals with the database
                }

            timer1.Start();
            }
4

1 に答える 1

0

確認すべき点がいくつかあります。

  1. EventLogソースが正しく構成されていることを確認してください( MSDN )。Windowsサービスへの私の答えは自動的に開始および停止しました。ここでも例外処理の問題が役立つ可能性があります。
  2. Windows フォーム タイマーを使用しているようです。これらには UI メッセージ ポンプが必要ですが、これはサービス ( MSDN ) にはありません。System.Threading代わりに、名前空間 ( MSDN )の Timer クラスを使用して調査する必要があります。

特に、 aを使用するSystem.Threading.Timerと、このオブジェクトが配管をもう少し管理してくれるので、コードが大幅に簡素化されることに気付くかもしれません。

を呼び出すこともお勧めしThread.Abort()ません。それは有害で予測できない可能性があり、あなたの場合、それを使用する必要はまったくないようです。CurrentThread.Abort または CurrentThread.Abortおよび http://msdn.microsoft.com/en-us/library/5b50fdsz.aspxを参照してください。

于 2012-12-14T23:46:03.130 に答える