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

时间:2015-06-30 04:51:37

标签: c# wpf multithreading parameters

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

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;
}

但在这种情况下,编译器会返回此错误:

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

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

我甚至不知道为什么:

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

首先运作。 "新线程" 的参数如何与所需的方法兼容?我在此页面上找到了这行代码:https://stackoverflow.com/a/1195915/2770195

有什么建议吗?

3 个答案:

答案 0 :(得分:0)

使用ParameterizedThreadStart Delegate。请参考:

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

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

希望得到这个帮助。

答案 1 :(得分:0)

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

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不存在。

答案 2 :(得分:0)

在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));
    }