存储具有多个参数的线程 - WPF

Store a thread with multiple parameters - WPF

我使用下面的代码 运行 一个带有多个参数的线程:

public Thread StartTheThread(System.Windows.Threading.Dispatcher dispatcher, int param1, string param2)
{
    Thread t = new Thread(() => Work(Maingrid.Dispatcher, param1, param2));
    t.Start();
    return t;
}

public delegate void delegate1(Color randomparam, Color secondparam);

public void Work(System.Windows.Threading.Dispatcher dispatcher, int param1, string param2)
{
    dispatcher.Invoke(new delegate1(update), {Color.FromRgb(255, 255, 0),Color.FromRgb(170, 255, 170)});
}

public void update(Color randomparam, Color secondparam)
{
    ...
}

创建新线程通常需要 "ThreadStart" 或 "ParameterizedThreadStart" 方法。 Threadstart 方法适用于没有参数的线程,parameterizedthreadstart 方法适用于只有 1 个参数(作为对象)的线程。但是我有不同类型的参数。由于这些方法是委托,我尝试使用自定义委托来存储线程以便稍后调用:

public delegate void starterdelegate(System.Windows.Threading.Dispatcher dispatcher, int param1, string param2);

public Thread StartTheThread(int param1, string param2)
{
    Thread t = new Thread(new starterdelegate(RealStart));
    ...
    return t;
}

但是在这种情况下,编译器 returns 这个错误:

“重载解析失败,因为无法使用这些参数调用可访问的 'New': 'Public Sub New(start As System.Threading.ParameterizedThreadStart)': 类型 'ThreadTraining.MainWindow.starterdelegate' 的值无法转换为 'System.Threading.ParameterizedThreadStart'。 'Public Sub New(start As System.Threading.ThreadStart)': 类型 'ThreadTraining.MainWindow.starterdelegate' 的值无法转换为 'System.Threading.ThreadStart'."

我的意思是运行ning多参数线程没有问题,但是当我要存储线程t的时候,我不想提交参数,因为它们会改到下次我运行跟帖。如果我使用 ParameterizedThreadStart 方法并且不提交参数,编译器将抛出签名错误。如果我不使用所需的方法之一,编译器将抛出重载解析失败错误。

我什至不知道这是为什么:

Thread t = new Thread(() => Work(Maingrid.Dispatcher, param1, param2));

工作第一。这里的"new Thread"的参数怎么兼容需要的方法?我在这个页面上找到了这行代码:

有什么建议吗?

使用 ParameterizedThreadStart 委托。参考这里:

https://msdn.microsoft.com/en-us/library/system.threading.parameterizedthreadstart(v=vs.110).aspx

我认为你应该创建一个新的 class 来封装你的参数,并将新的 class 实例作为参数发送到线程。

希望对您有所帮助。

您可以将参数封装在 class 中,但您也可以将您的逻辑封装在 class 中:

public class FooProcessor
{
    private readonly Color _color1;
    private readonly Color _color2;

    public FooProcessor(Color color1, Color color2)
    {
        _color1 = color1;
        _color2 = color2;
    }

    public Task ProcessAsync()
    {
        return Task.Run((Action) Process);
    }

    private void Process()
    {
        //add your logic here
    }
}

OT:如果您没有特定理由使用 Thread 而不是 Task,请使用 Task。一些较早的教程使用 Threads,因为当时 Task 不存在。

在 SO 上有关于将多个参数传递给 ThreadStart 方法的问题的答案。我喜欢这个:

    static void Main(string[] args)
    {
        for (int i = 1; i < 24; i++)
        {
            Thread t = new Thread( ()=>ThreadWorkingStuff(i,"2"+i.ToString() ));
            t.Start();
        }
        Console.ReadKey();
    }

    static void ThreadWorkingStuff(int a, string b)
    {
        Console.WriteLine(string.Format("Thread{2}|  a={0} b={1}", a, b, Thread.CurrentThread.ManagedThreadId));
    }