【发布时间】:2015-06-30 04:51:37
【问题描述】:
我使用下面的代码来运行具有多个参数的线程:
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;
}
但是在这种情况下,编译器会返回这个错误:
“重载解析失败,因为无法使用这些参数调用可访问的‘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'。"
我的意思是多参数运行线程没有问题,但是当我想存储线程t时,我不想提交参数,因为它们会在我下次运行时更改线。如果我使用 ParameterizedThreadStart 方法并且不提交参数,编译器会抛出签名错误。如果我不使用所需的方法之一,编译器将抛出重载解析失败错误。
我什至不知道这是为什么:
Thread t = new Thread(() => Work(Maingrid.Dispatcher, param1, param2));
首先工作。这里的“new Thread”的参数如何与所需的方法兼容?我在这个页面上找到了这行代码:https://stackoverflow.com/a/1195915/2770195
有什么建议吗?
【问题讨论】:
-
删除所有内容并使用
async/await。此外,无论您在做什么,都应该使用 DataBinding。 -
我真的不明白你想要达到什么目的。
-
@HighCore 你是什么意思?我不明白。
-
@OndrejJanacek 我只是不想提交参数来存储它们。为什么我需要?它只会消耗更多的冗余内存空间(因为我确信它的参数会在我下次运行它们之前发生变化)。出于这个原因,我觉得我做错了。一定有更好的办法
标签: c# wpf multithreading parameters