thread with multiple parameters

前端 未结 11 1568
一生所求
一生所求 2020-11-29 04:16

Does anyone know how to pass multiple parameters into a Thread.Start routine?

I thought of extending the class, but the C# Thread class is sealed.

Here is wh

11条回答
  •  醉梦人生
    2020-11-29 05:03

    I've been reading yours forum to find out how to do it and I did it in that way - might be useful for somebody. I pass arguments in constructor which creates for me working thread in which will be executed my method - execute() method.

     using System;
    
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Diagnostics;
    using System.Windows.Forms;
    using System.IO;
    using System.Threading;
    namespace Haart_Trainer_App
    
    {
        class ProcessRunner
        {
            private string process = "";
            private string args = "";
            private ListBox output = null;
            private Thread t = null;
    
        public ProcessRunner(string process, string args, ref ListBox output)
        {
            this.process = process;
            this.args = args;
            this.output = output;
            t = new Thread(new ThreadStart(this.execute));
            t.Start();
    
        }
        private void execute()
        {
            Process proc = new Process();
            proc.StartInfo.FileName = process;
            proc.StartInfo.Arguments = args;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.Start();
            string outmsg;
            try
            {
                StreamReader read = proc.StandardOutput;
    
            while ((outmsg = read.ReadLine()) != null)
            {
    
                    lock (output)
                    {
                        output.Items.Add(outmsg);
                    }
    
            }
            }
            catch (Exception e) 
            {
                lock (output)
                {
                    output.Items.Add(e.Message);
                }
            }
            proc.WaitForExit();
            var exitCode = proc.ExitCode;
            proc.Close();
    
        }
    }
    }
    

提交回复
热议问题