简体   繁体   中英

ThreadPool.QueueUserWorkItem adding delegate?

Reading through some code I found:

ThreadPool.QueueUserWorkItem(delegate { this.SaveInternal(); });

Why would someone put delegate here?

Usinng delegate like that is just a shortcut for passing any valid delegate that you don't care about the arguments while keeping the compiler happy. Otherwise you would have to pass a method that matches the delegate signature.

The most obvious answer is because the code won't compile without it. For example:

ThreadPool.QueueUserWorkItem( { this.SaveInternal(); });

Gives Invalid expression term '{'

QueueUserWorkItem requires a WaitCallback argument, which is a method that takes an Object parameter. The long form of what you have there is:

ThreadPool.QueueUserWorkItem((state) => { this.SaveInternal(); });

Which is the same as:

void Temp(Object state)
{
    this.SaveInternal();
}

ThreadPool.QueueUserWorkItem(Temp);

Adding delegate { this.SaveInternal(); } delegate { this.SaveInternal(); } allows the compiler to use type inference to resolve the apparent ambiguity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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