相关疑难解决方法(0)

委托.BeginInvoke和在C#中使用ThreadPool线程之间的区别

在C#中,使用委托异步地执行某些工作(调用BeginInvoke())和使用ThreadPool线程之间有任何区别,如下所示

public void asynchronousWork(object num)
    {
        //asynchronous work to be done
        Console.WriteLine(num);
    }

 public void test()
    {
        Action<object> myCustomDelegate = this.asynchronousWork;
        int x = 7;

        //Using Delegate
        myCustomDelegate.BeginInvoke(7, null, null);

        //Using Threadpool
        ThreadPool.QueueUserWorkItem(new WaitCallback(asynchronousWork), 7);
        Thread.Sleep(2000);
    }
Run Code Online (Sandbox Code Playgroud)

编辑:
BeginInvoke确保线程池中的线程用于执行异步代码,所以有什么区别吗?

c# multithreading threadpool

31
推荐指数
1
解决办法
1万
查看次数

C#使用ThreadPool执行方法(带参数)

我们有以下代码(在本网站上找到此代码的想法),它将为方法"Do_SomeWork()"生成新线程.这使我们能够异步多次运行该方法.

代码是:

    var numThreads = 20;
    var toProcess = numThreads;

    var resetEvent = new ManualResetEvent(false);

    for (var i = 0; i < numThreads; i++)
    {
        new Thread(delegate()
        {
            Do_SomeWork(Parameter1, Parameter2, Parameter3);
            if (Interlocked.Decrement(ref toProcess) == 0) resetEvent.Set();
        }).Start();
    }

    resetEvent.WaitOne();
Run Code Online (Sandbox Code Playgroud)

但是我们想要使用ThreadPool而不是创建我们自己的新线程,这可能对性能有害.问题是我们如何修改上面的代码以使用ThreadPool,记住方法"Do_SomeWork"采用多个参数并且还有一个返回类型(即方法不是void).

此外,这是C#2.0.

c# parameters multithreading threadpool

6
推荐指数
1
解决办法
2万
查看次数

.NET中的通用ThreadPool

对于我来说,这是一个相对常见的任务,我认为,对于许多.NET程序员来说:
我想使用.NET ThreadPool来调度需要处理给定类型任务的工作线程.

作为回顾,ThreadPool及其关联委托的排队方法的签名是:

public static bool QueueUserWorkItem (
    WaitCallback callBack,
    Object state
)
public delegate void WaitCallback (Object state)
Run Code Online (Sandbox Code Playgroud)

因此,典型的通用工作线程类看起来像:

public class Worker<T> {
    public void schedule(T i_task) {
        ThreadPool.QueueUserWorkItem(execute, i_task)
    }
    private void execute(Object o){
        T task = (T)o;  //What happened to the type safety?  
        executeTask(task);
    }
    private void executeTask(T i_task){
        //process i_task
    }
}
Run Code Online (Sandbox Code Playgroud)

注意state参数的类型?是的Object!

.NET团队选择不使QueueUserWorkItem方法(或整个ThreadPool类)通用的令人信服的原因是什么?我无法相信他们只是忽略了它.

这是我想看到它的方式:

//in the ThreadPool class:
public static bool QueueUserWorkItem<T> (
    WaitCallback<T> callBack,
    T …
Run Code Online (Sandbox Code Playgroud)

.net c# generics multithreading threadpool

5
推荐指数
2
解决办法
3748
查看次数

标签 统计

c# ×3

multithreading ×3

threadpool ×3

.net ×1

generics ×1

parameters ×1