how to use QueueUserWorkItem with ref/out state?
Is it possible to do:
ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ref data);
such that my Th开发者_运维问答readProc could make the caller's data point to a different location than when the call was originated?
If it is not possible, is there a way to implement such functionality with IntPtr or something?
Here you go, full working sample:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication19 {
class Program {
static object sync = new object();
static void Main(string[] args) {
int counter = 0;
ThreadPool.QueueUserWorkItem(new WaitCallback((_) => ThreadProc(ref counter)), null);
while (true) {
lock (sync) {
if (counter == 1) break;
}
Thread.Sleep(1);
}
Console.Write(counter);
Console.Read();
}
static void ThreadProc(ref int counter) {
lock (sync) {
counter++;
}
}
}
}
Note:
From a concurrency perspective, you are playing with fire big time. When this gets tricky you start risking deadlocks and all sort of nasties.
No, simply because the definition of WaitCallback(object state)
contains a non-ref parameter.
And if you could, it would be inherently un-threadsafe.
No, QueueUserWorkItem
does not support that signature, besides this would be a nightmare to debug in a Multi-Threaded Application.
No, and it would be inadvisable to try to implement the functionality yourself. The definition of a thread means you have no idea when it's going to modify the value of data
. Passing anything by reference to a thread would practically guarantee some sort of race condition or concurrency violation.
Its so simple. Use a class object as the state object. In fact, the reference to the class object will be passed by thread creation and therefore you will have the class public properties as mutual variables between the thread maker and the created thread.
精彩评论