Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用Threadpool时如何传递令牌和输入参数?_C#_Multithreading - Fatal编程技术网

C# 使用Threadpool时如何传递令牌和输入参数?

C# 使用Threadpool时如何传递令牌和输入参数?,c#,multithreading,C#,Multithreading,使用Threadpool时如何传递几个参数?我想做一些类似于PerformTest的事情(true、3、2、_cancellationTokenSourceObj.Token) 这是我使用它的方式,只传递取消令牌: _cancellationTokenSourceObj = new CancellationTokenSource(); ThreadPool.QueueUserWorkItem(new WaitCallback(PerformTest), _cancellationTokenSou

使用Threadpool时如何传递几个参数?我想做一些类似于PerformTest的事情(true、3、2、_cancellationTokenSourceObj.Token)

这是我使用它的方式,只传递取消令牌:

_cancellationTokenSourceObj = new CancellationTokenSource();
ThreadPool.QueueUserWorkItem(new WaitCallback(PerformTest), _cancellationTokenSourceObj.Token);
性能测试方法:

 public void PerformTest(object obj)
     {
         CancellationToken token = (CancellationToken)obj;
        ..
      }

如果您使用匿名函数,它将作为闭包工作,并且可以访问本地范围内的变量

bool arg0 = true;
int arg1 = 3;
int arg2 = 2;
CancellationTokenSource cancelTokenSource = new CancellationTokenSource();
ThreadPool.QueueUserWorkItem(obj =>
{
    CancellationToken token = (CancellationToken)obj;
    // PerformTest body here
    // This anonymous delegate is a closure and has access to arg0, arg1, and arg2.
}, cancelTokenSource.Token);

如果要继续使用命名函数,需要为参数创建一个数据结构,加上取消标记,并从命名函数中的对象参数强制转换它。

如果坚持使用此过时的API:

_cancellationTokenSourceObj = new CancellationTokenSource();
ThreadPool.QueueUserWorkItem(() => PerformTest(_cancellationTokenSourceObj.Token));

最好使用
任务。运行

为什么QueueUserWorkItem而不是任务?