dadag90
dadag90

Reputation: 33

C# rerun thread

I want to rerun thread when it finish working. I have two programs. One in Windows Form and second in cmd. Windows Form program run program in cmd.

I tried use while(true) and if with: process.HasExited, .WaitForExit, .Join on thred, .IsBusy and rerun method on RunWorkerCompleted. But it's doesn't work.

BgWorker code (action on button click):

        backgroundWorker1.RunWorkerAsync();
        backgroundWorker1.DoWork += new DoWorkEventHandler(uruchomWatek);

Function whitch I want to rerun thread

private void uruchomWatek(object sender, DoWorkEventArgs e)
{
    String polaczenieZDB = config.Default.adresDb + ";" + config.Default.nazwaDb + ";" + config.Default.login + ";" + config.Default.haslo;

    //przygotowuję proces 
    Process pr = new Process();
    ProcessStartInfo prs = new ProcessStartInfo();
    //uruchamiam cmd
    prs.FileName = "cmd";
    // /c START uruchamia program w cmd, przekazuję tutaj prametry
    prs.Arguments = " /c START " + " " + @sciezkaDoSlaveTextBox.Text + " " + ipAdresTextBox.Text + " "
                    + numerPortuTextBox.Text + " " + polaczenieZDB + " " + pobierzZadaniaDoSpr();
    pr.StartInfo = prs;

    //uruchamiam proces w nowym wątku
    ThreadStart ths = new ThreadStart(() => pr.Start());
    Thread th = new Thread(ths);
    th.IsBackground = true;
    th.Start();
}

Upvotes: 3

Views: 138

Answers (1)

Mohammad Chamanpara
Mohammad Chamanpara

Reputation: 2159

This class may help you through this purpose :

 public class BackgroundThread : BackgroundWorker
    {
        public BackgroundThread()
        {
            this.WorkerSupportsCancellation = true;
        }
        protected override void OnDoWork(DoWorkEventArgs e)
        {
            try
            {
                base.OnDoWork(e);
            }
            catch (Exception exception)
            {
                //Log Exception
            }
        }
        public void Run()
        {
            if (this.IsBusy)
                return;
            this.RunWorkerAsync();
        }
        public void Stop()
        {
            this.CancelAsync();
            this.Dispose(true);
        }
    }

EDIT :

If you want to use your class as a timer and do the task in intervals the following class may comes really handy.

  public class BackgroundTimer : BackgroundWorker
    {
        private ManualResetEvent intervalManualReset;
        private enum ProcessStatus { Created, Running, JobCompleted, ExceptionOccured };
        private ProcessStatus processStatus = new ProcessStatus();
        public int Interval { get; set; }

        public BackgroundTimer()
        {
            this.processStatus = ProcessStatus.Created;
            this.WorkerSupportsCancellation = true;
            this.Interval = 1000;
        }

        protected override void OnRunWorkerCompleted(RunWorkerCompletedEventArgs e)
        {
            base.OnRunWorkerCompleted(e);
            if (processStatus == ProcessStatus.ExceptionOccured)
                // Log ...  
            processStatus = ProcessStatus.JobCompleted;
        }
        protected override void OnDoWork(DoWorkEventArgs e)
        {
            while (!this.CancellationPending)
            {
                try
                {
                    base.OnDoWork(e);
                    this.Sleep();
                }
                catch (Exception exception)
                {
                    // Log ...
                    this.processStatus = ProcessStatus.ExceptionOccured;
                    this.Stop();
                }
            }
            if (e != null)
                e.Cancel = true;
        }

        public void Start()
        {
            this.processStatus = ProcessStatus.Running;
            if (this.IsBusy)
                return;

            this.intervalManualReset = new ManualResetEvent(false);
            this.RunWorkerAsync();
        }
        public void Stop()
        {
            this.CancelAsync();
            this.WakeUp();
            this.Dispose(true);
        }
        public void WakeUp()
        {
            if (this.intervalManualReset != null)
                this.intervalManualReset.Set();
        }
        private void Sleep()
        {
            if (this.intervalManualReset != null)
            {
                this.intervalManualReset.Reset();
                this.intervalManualReset.WaitOne(this.Interval);
            }
        }
        public void Activate()
        {
            if (!this.IsBusy)
                // Log ...
            this.Start();
        }
    }

EDIT 2 : Usage :

    sendThread = new BackgroundThread();
    sendThread.DoWork += sendThread_DoWork;
    sendThread.Run();
    void sendThread_DoWork(object sender, DoWorkEventArgs e)
    {
       ...
    }

Upvotes: 1

Related Questions