gpt4 book ai didi

c# - System.Threading.ThreadPool.QueueUserWorkItem C# 的动态回调方法

转载 作者:行者123 更新时间:2023-12-03 12:49:52 24 4
gpt4 key购买 nike

我想要做的是能够将函数引用传递给另一个函数,并将其用作 System.Threading.ThreadPool.QueueUserWorkItem 的回调方法。

请参阅方法 D() 中的“任何”参数。

我需要能够为“任何”参数传递回调方法指针或引用。我不能使用委托(delegate),因为那需要是静态的,对吗?

有任何想法吗?

    private void A() { /*code*/ }

private void B() { /*code*/ }

private void C(int i)
{
switch(i)
{
case 1:
D(A());
break;
case 2:
D(B());
break;
default:
break;
}
}

private void D(type? Any)
{
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(Any));
}

最佳答案

I can't use a delegate, because that would need to be static, is that correct.



不,这是不正确的。
delegate void MyMethods();

class Foo
{
void Minstance() {}
static void Mstatic() {}

MyMethods m1 = Minstance; // OK
MyMethods m2 = Mstatic; // OK
}

以下是不正确的语法:
        case 1:
D(A()); // here you call (execute) A
break;

只需省略方法后的括号:
        case 1:
D(A); // this passes a reference to A
break;

现在你必须正确定义 D :
void D(WaitCallback any)
{
ThreadPool.QueueUserWorkItem(any);
}

关于c# - System.Threading.ThreadPool.QueueUserWorkItem C# 的动态回调方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7603245/

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