gpt4 book ai didi

C# 使用对成员函数的委托(delegate)来创建新线程

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:17 24 4
gpt4 key购买 nike

我想为成员函数创建一个新线程。我目前使用此代码,

Thread thread = new Thread(new ThreadStart(c.DoSomethingElse));
thread.Start();

它正在运行。但现在我想参数化成员函数。

我有这门课:

class C1 {
public void DoSomething() {}
public void DoSomethingElse() {}

public delegate void myDelegate(C1 c);
}

然后我在其他一些类中有这个功能:

public void myFunction(C1.myDelegate func) {
C1 c = new C1();

func(c); // this is working

// but I want that the called function runs in it's own thread
// so I tried...
Thread thread = new Thread(new ThreadStart( func(c) ); // but the compile wants a
thread.Start(); // method name and not a delegate
}

我调用 myFunction 如下...

myFunction( (c) => c.DoSomething() );

那么有没有可能做到这一点。我的意思是,我可以传递委托(delegate)并使用对象 func(c) 调用它。我可以创建一个传递 object.memberfunction 的新线程。但我不知道如何将两者结合起来,使用成员函数委托(delegate)并将其传递给 ThreadStart 函数。有什么提示吗?

最佳答案

我建议使用 .NET 中内置的并行机制。

Task.Factory.StartNew(() => func(c));

关于C# 使用对成员函数的委托(delegate)来创建新线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17821145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com