繁体   English   中英

WPF C#线程

[英]WPF C# Threading

我正在用C#编写代码来进行图像处理。 我想使用线程,并且我想WPF应用程序中的线程几乎没有什么不同。 我试图运行线程,但仅在函数为void()时才起作用,即不接受任何参数。

但是,我的职能是要像这样辩论3次

frame_extract.Frame_Processing(_colorFrame_, widht, height);

因此,以下内容不起作用

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

也许我缺少了一些东西,但是我的问题是我该如何处理带有参数的函数的线程。

也许您可以使用TPL。

然后应该是这样的:

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

但是请注意,您可能必须编组到ui线程。

如果要在ui线程中创建线程,并希望新线程与提到的ui线程进行交互,则应执行以下操作:

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

那应该工作。

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

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和obj强制转换为像此object arr = obj as object[];一样的对象数组object arr = obj as object[]; 然后您可以访问这3个参数,例如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;

3)创建并启动您的线程

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM