我正在查看有关RegisterWaitForSingleObject
HERE的MSDN,并在示例中发现了这种用法-
ti.Handle = ThreadPool.RegisterWaitForSingleObject(
ev,
new WaitOrTimerCallback(WaitProc),
ti,
1000,
false
);
其中WaitProc
为方法-
public static void WaitProc(object state, bool timedOut)
{
//Code
}
我也发现了同样的例子,通过替换WaitProc
方法类似于这个-
ti.Handle = ThreadPool.RegisterWaitForSingleObject(
ev,
(state, timedOut) => {
//code blah blah
//manipulate state
//manipulate timedOut
}
ti,
1000,
false
);
这里我假设方法RegisterWaitForSingleObject
期望WaitOrTimerCallback
方法,编译器理解这一点并将(state, timedOut)
视为方法,因此变量可以在调用本身中使用。
这个概念叫什么?
它是如何工作的?
这个概念叫什么?
它是如何工作的?
称为Lambda表达式。编译器接受表达式并将其翻译为一个命名方法,同时省去了每次实际定义一个与委托签名匹配的命名方法的麻烦。
使用TryRoslyn,这是你的委托编译下来的内容(在新的Roslyn编译器上):
private sealed class <>c
{
public static readonly C.<>c <>9;
public static WaitOrTimerCallback <>9__0_0;
static <>c()
{
// Note: this type is marked as 'beforefieldinit'.
C.<>c.<>9 = new C.<>c();
}
internal void <M>b__0_0(object state, bool timedOut)
{
}
}
public void M()
{
Mutex mutex = new Mutex();
WaitHandle arg_2E_0 = mutex;
WaitOrTimerCallback arg_2E_1;
if (arg_2E_1 = C.<>c.<>9__0_0 == null)
{
arg_2E_1 = C.<>c.<>9__0_0 = new WaitOrTimerCallback(C.<>c.<>9.<M>b__0_0);
}
RegisteredWaitHandle registeredWaitHandle =
ThreadPool.RegisterWaitForSingleObject(arg_2E_0, arg_2E_1, null, 1000, false);
}