WPF C# Threading

本文关键字:Threading WPF | 更新日期: 2023-09-27 18:18:05

我正在用c#写一个代码来做图像处理。我想使用线程,我想WPF应用程序中的线程略有不同。我试图运行线程,但它只工作时,函数是void(),即不接受任何参数。

然而,我的函数像这样接受3个参数

frame_extract.Frame_Processing(_colorFrame_, widht, height);

因此下面的语句不起作用

depth_Threads = new System.Threading.Thread(**) since ** takes on void() type.

也许我错过了一些东西,但我的问题是我如何能够使用线程的函数,接受参数

WPF C# Threading

也许你可以使用TPL。

应该是这样的:

Task.Factory.StartNew(() => frame_extract.Frame_Processing(_colorFrame_, widht, height));

但是要注意,您可能必须封送到ui-thread。

如果你想在ui线程中创建线程,并希望新线程与提到的ui线程交互,应该像下面这样工作:

var task = new Task(() => frame_extract.Frame_Processing(_colorFrame_, widht, height));
task.Start(TaskScheduler.FromCurrentSynchronizationContext());

应该可以。

我不确定这是否是你想要的,但我认为你需要这样做:

depth_Threads = new System.Threading.Thread(()=>frame_extract.Frame_Processing(_colorFrame_, widht, height));

这取决于您传入的值。有时,如果您正在使用对象,则它们被锁定在给定的线程中,在这种情况下,您需要事先创建副本,然后将副本传递给新线程。

执行以下操作。你的方法应该接收像void SomeVoid(object obj)这样的单个对象参数。创建一个对象数组,包含你想传递给SomeVoid方法的所有变量,比如object[] objArr = { arg1, arg2, arg3 };,然后使用objArr参数调用线程对象的Start方法,因为Start()方法接收一个对象参数。现在回到你的方法,将从Start方法接收到的obj转换为一个对象数组,比如object arr = obj as object[];然后你可以访问这三个参数,比如arr[0] arr[1]arr[2]

您可以使用ParameterizedThreadStart

1)创建一个包含三个参数的类

 public class FrameProcessingArguments
 {
     public object ColorFrame { get; set; }
     public int Width { get; set; }
     public int Height { get; set; }
 }

2)修改你的Frame_Processing方法,将Object的实例作为参数,并在其中将该实例转换为FrameProcessingArguments

if (arguments == null) throw new NullArgumentException();
if(arguments.GetType() != typeof(FrameProcessingArguments)) throw new InvalidTypeException();
FrameProcessingArguments _arguments = (FrameProcessingArguments) arguments;
创建并启动你的线程
FrameProcessingArguments arguments = new FrameProcessingArguments() 
{
     ColorFrame = null,
     Width = 800,
     Height = 600
}
Thread thread = new Thread (new ParameterizedThreadStart(frame_extract.Frame_Processing));
// You can also let the compiler infers the appropriate delegate creation syntax:
// and use the short form : Thread thread = new Thread(frame_extract.Frame_Processing);
thread.Start (arguments);