如何使用Ref/out状态的QueueUserWorkItem? [英] how to use QueueUserWorkItem with ref/out state?

查看:81
本文介绍了如何使用Ref/out状态的QueueUserWorkItem?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以这样做吗?

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

这样我的ThreadProc可以使调用者的数据指向与发起呼叫时不同的位置?

such that my ThreadProc could make the caller's data point to a different location than when the call was originated?

如果不可能的话,有没有办法用IntPtr或其他东西来实现这种功能?

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++;
            }
        }
    }
}

注意:

从并发角度来看,您正在玩​​大量的时间.当这变得棘手时,您将开始面临僵局和各种麻烦.

From a concurrency perspective, you are playing with fire big time. When this gets tricky you start risking deadlocks and all sort of nasties.

这篇关于如何使用Ref/out状态的QueueUserWorkItem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆