带有函数参数的ThreadPool.QueueUserWorkItem [英] ThreadPool.QueueUserWorkItem with function argument

查看:66
本文介绍了带有函数参数的ThreadPool.QueueUserWorkItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#2.0,并且想借助 ThreadPool.QueueUserWorkItem 调用带有几个参数的方法,所以我尝试如下:

I am using C# 2.0 and want to call a method with a couple of parameters with the help of ThreadPool.QueueUserWorkItem, so I tried as follows:

ThreadPool.QueueUserWorkItem(new WaitCallback(Multiply(2, 3)));

private int Multiply(int x,int y)
{
  int z=(x*y);
  return z;
}

我遇到编译错误。因此,请指导我,如何使用 ThreadPool.QueueUserWorkItem 调用具有多个参数的函数?

I am getting compilation error. So please guide me, how can I call a function with multiple arguments with ThreadPool.QueueUserWorkItem?.

我有另一个查询,当我使用 ThreadPool.QueueUserWorkItem 时,如何在此处使用匿名函数我可以在那里编写代码,而不用调用另一个函数。如果可以在C#v2.0中使用,请为我提供代码。

I have another query that when I am using ThreadPool.QueueUserWorkItem then how to use here anonymous function as a result I can write the code there instead of calling another function. If it is possible in C# v2.0 then please guide me with code.

推荐答案

您应该声明一个具有相同方法的方法定义为WaitCallback委托。您可以使用以下代码段:

You should declare a method which have the same definition as WaitCallback delegate. You can use the following code snippet:

ThreadPool.QueueUserWorkItem(Multiply, new object[] { 2, 3 }); 

public static void Multiply(object state)
{
    object[] array = state as object[];
    int x = Convert.ToInt32(array[0]);
    int y = Convert.ToInt32(array[1]);
}

匿名代表版本为:

 ThreadPool.QueueUserWorkItem(delegate(object state)
    {
        object[] array = state as object[];
        int x = Convert.ToInt32(array[0]);
        int y = Convert.ToInt32(array[1]);
    }
    , new object[] { 2, 3 });

这篇关于带有函数参数的ThreadPool.QueueUserWorkItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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