views:

96

answers:

3

Is it possible to do:

ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ref data);

such that my ThreadProc 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?

+1  A: 

No, QueueUserWorkItem does not support that signature, besides this would be a nightmare to debug in a Multi-Threaded Application.

Stan R.
+1  A: 

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.

Aaronaught
+2  A: 

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.

Sam Saffron
@sam..i didn't want to post any code examples, because this is VERY VERY dangerous. I don't think i'd be able to sleep at night if I found this code somewhere :)..but +1 for a full example
Stan R.