문제

사람을 통과하는 방법을 알고 여러 매개 변수는 스레드가 있습니다.시작 일과?

나는 생각의 클래스를 확장하지만,C#Thread 등이 밀봉된다.

여기에 내가 무엇을 생각하는 코드는 다음과 같다:

...
    Thread standardTCPServerThread = new Thread(startSocketServerAsThread);

    standardServerThread.Start( orchestrator, initializeMemberBalance, arg, 60000);
...
}

static void startSocketServerAsThread(ServiceOrchestrator orchestrator, List<int> memberBalances, string arg, int port)
{
  startSocketServer(orchestrator, memberBalances, arg, port);
}

BTW,시작하는 쓰레드의 수와 다른 orchestrators 로 균형과 항구가 있습니다.을 고려하시기 바랍 스레드에 안전한다.

도움이 되었습니까?

해결책

람다 표현식을 사용하여 인수를 포착하십시오.

Thread standardTCPServerThread = 
  new Thread(
    unused => startSocketServerAsThread(initializeMemberBalance, arg, 60000)
  );

다른 팁

다음은 여기에 언급 된 객체 배열 접근법을 몇 번 사용하는 약간의 코드입니다.

    ...
    string p1 = "Yada yada.";
    long p2 = 4715821396025;
    int p3 = 4096;
    object args = new object[3] { p1, p2, p3 };
    Thread b1 = new Thread(new ParameterizedThreadStart(worker));
    b1.Start(args);
    ...
    private void worker(object args)
    {
      Array argArray = new object[3];
      argArray = (Array)args;
      string p1 = (string)argArray.GetValue(0);
      long p2 = (long)argArray.GetValue(1);
      int p3 = (int)argArray.GetValue(2);
      ...
    }>

당신은 그것들을 단일 객체로 감해야합니다.

매개 변수에서 전달할 사용자 정의 클래스를 만드는 것은 하나의 옵션입니다. 배열 또는 객체 목록을 사용하여 모든 매개 변수를 설정할 수도 있습니다.

'작업'패턴 사용 :

public class MyTask
{
   string _a;
   int _b;
   int _c;
   float _d;

   public event EventHandler Finished;

   public MyTask( string a, int b, int c, float d )
   {
      _a = a;
      _b = b;
      _c = c;
      _d = d;
   }

   public void DoWork()
   {
       Thread t = new Thread(new ThreadStart(DoWorkCore));
       t.Start();
   }

   private void DoWorkCore()
   {
      // do some stuff
      OnFinished();
   }

   protected virtual void OnFinished()
   {
      // raise finished in a threadsafe way 
   }
}

.NET 2 Jaredpar 답변의 변환

Thread standardTCPServerThread = new Thread(delegate (object unused) {
        startSocketServerAsThread(initializeMemberBalance, arg, 60000);
    });

당신은 할 수 없습니다. 필요한 매개 변수를 포함하는 객체를 만듭니다. 스레드 함수에서 객체를 유형으로 다시 캐스팅합니다.

void RunFromHere()
{
    string param1 = "hello";
    int param2 = 42;

    Thread thread = new Thread(delegate()
    {
        MyParametrizedMethod(param1,param2);
    });
    thread.Start();
}

void MyParametrizedMethod(string p,int i)
{
// some code.
}

나는 당신의 포럼을 읽고 그것을하는 방법을 알아 내고 그런 식으로 그렇게했습니다 - 누군가에게 유용 할 것입니다. 제작자에 인수를 전달하여 작업 스레드를 만들어 내 메소드가 실행됩니다. 실행하다() 방법.

 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();

    }
}
}

객체 배열을 가져 와서 스레드에 전달할 수 있습니다. 통과하다

System.Threading.ParameterizedThreadStart(yourFunctionAddressWhichContailMultipleParameters) 

스레드 생성자로.

yourFunctionAddressWhichContailMultipleParameters(object[])

당신은 이미 Objarray에서 모든 값을 설정했습니다.

당신은 필요합니다 abcThread.Start(objectArray)

할 수 있는 카레가"work"기능으로 람다 식:

public void StartThread()
{
    // ...
    Thread standardTCPServerThread = new Thread(
        () => standardServerThread.Start(/* whatever arguments */));

    standardTCPServerThread.Start();
}

단일 객체를 전달해야하지만 단일 사용을 위해 자신의 객체를 정의하기에는 너무 번거 로움이 있다면 튜플.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top