如何在 C# 中包装要在线程上执行的方法(带有参数列表)

本文关键字:方法 参数 列表 包装 线程 执行 | 更新日期: 2023-09-27 18:33:11

我有一个方法,看起来像:

public static int RandomNumber(int min, int max)
{
  return random.Next(min, max);
}

我想通过线程调用的委托包装此方法,该怎么做?

提前致谢

如何在 C# 中包装要在线程上执行的方法(带有参数列表)

不确定"包装"是什么意思,无论如何您可以使用Func委托引用该方法:

Func<int, int, int> myDelegate = RandomNumber;

然后你可以这样称呼它:

int rnd = myDelegate(1, 2);

这可能是您的线程代码:

private Thread thread;
public int RandomNumber(int min, int max)
{
    return random.Next(min, max);
}
public void RandomNumberProc(object state)
{
    int[] array = state as int[];
    RandomNumber(array[0], array[1]);
}
prublic void StartThread()
{
    thread = new Thread(RandomNumberProc);
    thread.IsBackground = true;
    thread.Start(new[] { 1, 2 });
}