C#并行开发_Thread/ThreadPool, Task/TaskFactory, Parallel

本文介绍了C#中的并行开发,包括Thread类、ThreadPool、Task和TaskFactory、Parallel类以及并行编程的同步方法。详细讨论了各种并行方式的适用场景、优缺点,如ThreadPool的高效但限制较多,Task类的优势在于定义后续任务和任务组织。还展示了如何使用Parallel.For和Parallel.ForEach进行并行操作。
摘要由CSDN通过智能技术生成
大家好,本次讨论的是C#中的并行开发,给力吧,随着并行的概念深入,哥也赶上这个潮流了,其实之前讨论C#的异步调用或者C#中BeginInvoke或者Invoke都已经涉及了部分本篇的内容。

参考书目:Professional.C#.4.0.and.NET.4.pdf 以及 Pro .NET 4 Parallel Programming in C#.pdf

Parallel Program in C#中有Delegate的Asynchronous也有Thread的Asynchronous,前者已经在《C#异步调用详细》中阐述清楚了,那它跟Thread的有什么区别呢?

可能大家都混淆了,我也快糊涂了,C#中异步(并行)编程有几类:

1. Asynchronous Delegates
        Asychronous calling is used when you have work items that should be handled in the background and you care when they finish.

2. BackgroundWorker
        Use BackgroundWorker if you have a single task that runs in the background and needs to interact with the UI. and use it if you don't care when they finish their task. The task of marshalling data and method calls to the UI thread are handled automatically through its event-based model.
        Avoid BackgroundWorker if (1) your assembly does not already reference the System.Windows.Form assembly, (2) you need the thread to be a foreground thread, or (3) you need to manipulate the thread priority.

3. ThreadPool

        Use a ThreadPool thread when efficiency is desired. The ThreadPool helps avoid the overhead associated with creating, starting, and stopping threads.
        Avoid using the ThreadPool if (1) the task runs for the lifetime of your application, (2) you need the thread to be a foreground thread, (3) you need to manipulate the thread priority, or (4) you need the thread to have a fixed identity (aborting, suspending, discovering).

4. Thread class
        Use the Thread class for long-running tasks and when you require features offered by a formal threading model, e.g., choosing between foreground and background threads, tweaking the thread priority, fine-grained control over thread execution, etc.

5. Task Parallel Library
        Task/TaskFactory, Parallel.For, Parallel.ForEach, Parallel.Invoke

6. Parallel LINQ

       TBD

好了进入主题了,先来介绍Thread命名空间。

Thread class

创建与指定委托(Create):
can be constructed with two kinds of delegate:
1. ThreadStart: void ()(void)
2. ParameterizedThreadStart: void ()(Object obj)
跟Asynchronous delegate 相比,输入参数已经很受限制,才支持一个,而且还是object对象的,没有进行类型检查。

控制:
Start() or Start(obj)
Start是直接让新创建的异步执行,类似于Asynchronous的BeginInvoke方法,就是异步于caller来执行。

下面的代码分别显示Asynchronous Delegate以及Thread做同样的事情
Asynchronous Delegate部分

        public void AsyncOperation(int data)
        {
            int i = 0;
            while (i++ < data)
            {
                Thread.Sleep(1000);
                Console.WriteLine(string.Format("Running for {0} seconds, in thread id: {1}.", i, Thread.CurrentThread.ManagedThreadId));
            }
        }
        public delegate void AsyncOperationDelegate(int data);
        public void RunBeginInvoke()
        {
            AsyncOperationDelegate d1 = new AsyncOperationDelegate(AsyncOperation);
            d1.BeginInvoke(3, null, null);
            int i = 0;
            while (i++ < 3)
            {
                Thread.Sleep(1000);
                Console.WriteLine(string.Format("[BeginInvoke]Running for {0} seconds, in thread id: {1}.", i, Thread.CurrentThread.ManagedThreadId));
            }
        }

Thread部分:
        private void AsyncOperation(object obj)
        {
            int data = (int)obj;
            int i = 0;
            while (i++ < data)
            {
                Thread.Sleep(1000);
                Console.WriteLine(string.Format("Running for {0} seconds, in thread id: {1}.", i, Thread.CurrentThread.ManagedThreadId));
            }
        }
        public void RunThread()
        {
            Thread t1 = new Thread(new ParameterizedThreadStart(AsyncOperation));
            t1.Start((object)3);
            int i = 0;
            while (i++ < 3)
            {
                Thread.Sleep(1000);
                Console.WriteLine(string.Format("[Thread]Running for {0} seconds, in thread id: {1}.", i, Thread.CurrentThread.ManagedThreadId));
            }
        }

使用起来比Asynchronous Delegate实在别扭以及难看。
书中提议使用类的成员函数作为委托函数,同时由于类成员函数能否访问类的成员变量,从而实现复杂或者多个参数传递,或者获取修改后的值。具体例子如下:

    class ThreadData
    {
        public int data = 0;
        public ThreadData()
        { 
        
        }

        public void RunThread()
        { 
            int i = 0;
            while (i++ < 1000000)
                data++;
  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值