码迷,mamicode.com
首页 > Windows程序 > 详细

C#5.0 异步编程

时间:2017-10-01 12:23:26      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:fun   void   包装   ...   封装   call   span   runas   ide   

委托的BeginInvoke实现异步

技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication1
{
    public delegate int MyDelegate(int x);
    class Program
    {
        static void Main(string[] args)
        {
            MyDelegate del = new MyDelegate((a) =>
            {
                Console.WriteLine("Sub Thread Begin");
                Thread.Sleep(2000);
                return 1;
            });
            //delegate的BeginInvoke方法实现异步调用
            del.BeginInvoke(1, (a) => { Console.WriteLine("Sub Thread Callback"); }, null);
            Console.WriteLine("Main Thread Over");
            Console.Read();
        }
    }
}
delegate的BeginInvoke

C#5.0 Async函数线性编程 方式实现异步编程

技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main Thread Begin");
            MyFunc();
            Console.WriteLine("Main Thread Over");
            Console.Read();
        }

        static async void MyFunc()
        {
            Console.WriteLine("MyFunc Begin");
            //程序执行到这里开启异步任务
            await Task.Run(() =>
            {
                Console.WriteLine("耗时操作开始");
                Thread.Sleep(2000);
                Console.WriteLine("耗时操作结束");
            });
            Console.WriteLine("MyFunc Over");
        }
    }
}
C#5.0异步函数

C#5.0 Async函数包装方法

技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main Thread Begin");
            new TestClass().DisplayResult();
            Console.WriteLine("Main Thread Over");
            Console.Read();
        }
    }

    class TestClass
    {
        public async void DisplayResult()
        {
            Console.WriteLine("耗时操作开始");
            //在异步函数中异步调用封装为Task的函数
            int res = await GetResultAsync(2);
            Console.WriteLine(res);
            Console.WriteLine("耗时操作结束");
        }
        //将耗时操作封装到Task函数中
        public Task<int> GetResultAsync(int n)
        {

            return Task.Run(() =>
            {
                Thread.Sleep(3000);
                return n + 1;
            });

        }
    }
}
C#5.0异步函数

封装函数异步执行

技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Main Thread Begin");
            TaskAsyncHelper.RunAsync(new Func<int, int>(MyFunc), new Action<int>(DisplayResult), 2);
            Console.WriteLine("Main Thread Over");
            Console.Read();
        }
        static int MyFunc(int i)
        {
            Console.WriteLine("耗时操作开始");
            Thread.Sleep(3000);
            return i + 10;
        }
        static void DisplayResult(int i)
        {
            Console.WriteLine("结果是:" + i);
            Console.WriteLine("耗时操作结束");
        }
    }

    //封装共通函数,传入函数后和回调函数后异步执行
    public static class TaskAsyncHelper
    {
        public static async void RunAsync<TResult>(Func<int, TResult> function, Action<TResult> callback, int num)
        {
            //将传入的函数封装为Task
            Func<Task<TResult>> taskFunc = () =>
            {
                return Task.Run(() =>
                {
                    return function(num);
                });
            };

            //异步执行封装的Task
            TResult res = await taskFunc();
            if (callback != null)
            {
                callback(res);
            }
        }
    }
}
把传入的函数封装为异步执行

信号量控制线程数量

技术分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        //声明信号量,表示同一资源最大线程数是3
        static SemaphoreSlim semLim = new SemaphoreSlim(3);
        static void Main(string[] args)
        {
            Console.WriteLine("Main Thread Begin");
            for (int i = 0; i < 20; i++)
            {
                new Thread(SemaphoreTest).Start();
            }
            Console.WriteLine("Main Thread Over");
            Console.Read();
        }

        static void SemaphoreTest()
        {
            semLim.Wait(); //阻塞当前线程,直到信号量释放
            Console.WriteLine("线程"+Thread.CurrentThread.ManagedThreadId.ToString()+"执行开始...");
            Thread.Sleep(2000);
            Console.WriteLine("线程" + Thread.CurrentThread.ManagedThreadId.ToString() + "执行结束...");
            semLim.Release();//释放信号量
        }
    }
}
信号量控制线程数

 

C#5.0 异步编程

标签:fun   void   包装   ...   封装   call   span   runas   ide   

原文地址:http://www.cnblogs.com/aaron-song/p/7616880.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!