• 多线程 笔记


    public class ThreadTest
        {
            /*
             * 1.由于工作窃取(work-stealing)队列而发起了大量任务,
             * 那么Task提供了比ThreadPool.QueueUserWorkItem或者
             * 一个委托的BeginInvoke更好的性能。
             * 2.可以使用PreferFairness标志,获取与ThreadPool.QueueUserWorkItem或者
             * 一个委托的BeginInvoke相同的线程池行为。
             * 3.可用一个自定义的TaskScheduler更改调度算法,同时不更改代码或编程模型。
             * 4.
             */
            public static void TestConext()
            {
                System.Runtime.Remoting.Messaging.CallContext.LogicalSetData("Name",
                    "jeffrey");
                ThreadPool.QueueUserWorkItem(state => Console.WriteLine("name={0}",
                    System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("Name")));
                //阻止main线程的执行上下文的流动
                ExecutionContext.SuppressFlow();
    
                ThreadPool.QueueUserWorkItem(state => Console.WriteLine("name={0}",
                    System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("Name")));
                ExecutionContext.RestoreFlow();
            }
    
            public static void Test()
            {
                Console.WriteLine("main thread:queuing an asyn operation");
                ThreadPool.QueueUserWorkItem(ComputeBound,23);
                Console.WriteLine("main thread: doing other work here...");
                Thread.Sleep(10000);
                Console.WriteLine("dddd");
            }
            private static void ComputeBound(object obj)
            {
                Console.WriteLine("in ComputeBound:state={0}", obj);
                Thread.Sleep(1000);
            }
            private static void TestWebRequest()
            {
                WebRequest request = WebRequest.Create("");
                request.BeginGetResponse(result =>
                {
                    WebResponse response = null;
                    try
                    {
                        response = request.EndGetResponse(result);
                        Console.WriteLine("content length: " + response.ContentLength);
                    }
                    catch (WebException we)
                    {
                        Console.WriteLine("failed: " + we.Message);
                    }
                    finally
                    {
                        if (response != null)
                            response.Close();
                    }
                }, null);
            }
            private static void TestWebRequestWithTask()
            {
                WebRequest request = WebRequest.Create("http://sssssss.com/");
                Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse,
                    request.EndGetResponse, null, TaskCreationOptions.None)
                    .ContinueWith(task =>
                    {
    
                    });
                request.BeginGetResponse(result =>
                {
                    WebResponse response = null;
                    try
                    {
                        response = request.EndGetResponse(result);
                        Console.WriteLine("content length: " + response.ContentLength);
                    }
                    catch (WebException we)
                    {
                        Console.WriteLine("failed: " + we.Message);
                    }
                    finally
                    {
                        if (response != null)
                            response.Close();
                    }
                }, null);
            }
    
        }
        internal static class CancellationDemo 
        {
            public static void Go() 
            {
                CancellationTokenSource cts = new CancellationTokenSource();
    
                ThreadPool.QueueUserWorkItem(o => Count(cts.Token, 100));
                Console.WriteLine("press <enter>");
                Thread.Sleep(5000);
                cts.Cancel();
            }
    
            private static void Count(CancellationToken cancellationToken, int countTo)
            {
                for (int count = 0; count < countTo; count++)
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        Console.WriteLine("Count is cancelled");
                        break;
                    }
                    Console.WriteLine(count);
                    Thread.Sleep(200);
                }
                Console.WriteLine("count is done");
            }
        }
        public class TestTask
        {
            private static int Sum(int n)
            {
                int sum = 0;
                for (; n > 0; n--)
                {
                    checked { sum += n; }
                }
                return sum;
            }
            public static void test()
            {
                //Task<int> t = new Task<int>(n => Sum((int)n), 10000);
                Task<int> t = new Task<int>(() => Sum(10000));
                t.Start();
                
                Console.WriteLine("the sum is:{0}", t.Result);
            }
            public static void test2()
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                Task<int> t = new Task<int>(() => Sum(cts.Token, 10000), cts.Token);
                t.Start();
                cts.Cancel();
                try
                {
                    Console.WriteLine("the sum is:{0}", t.Result);
                }
                catch (AggregateException x)
                {
                    x.Handle(e => e is OperationCanceledException);
                    Console.WriteLine(x.Message);
                    Console.WriteLine("sum was canceled");
                }
            }
            public static void test3()
            {
                //Task<int> t = new Task<int>(n => Sum((int)n), 10000);
                Task<int> t = new Task<int>(() => Sum(10000));
                t.Start();
                //如果调用wait或在任务还未完成时查询任务的Result属性,极有可能造成线程池创建一个新的线程,
                //这增大了资源的消耗,并影响了伸缩性。可用如下解决。
                t.ContinueWith(task => Console.WriteLine("the sum is:{0}", task.Result));
            }
            public static void test4()
            {
                //Task<int> t = new Task<int>(n => Sum((int)n), 10000);
                Task<int> t = new Task<int>(() => Sum(100000));
                t.Start();
    
                t.ContinueWith(task => Console.WriteLine("the sum is:{0}", task.Result),
                    TaskContinuationOptions.OnlyOnRanToCompletion);
                t.ContinueWith(task => Console.WriteLine("sum Exception:{0}", task.Exception),
                    TaskContinuationOptions.OnlyOnFaulted);
                t.ContinueWith(task => Console.WriteLine("sum Canceled"),
                    TaskContinuationOptions.OnlyOnCanceled);
            }
            private static int Sum(CancellationToken cancellationToken, int n)
            {
                int sum = 0;
                for (; n > 0; n--)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    checked { sum += n; }
                }
                return sum;
            }
            public static void TestParent()
            {
                Task<int[]> parent = new Task<int[]>(()=>{
                    var results = new int[3];
                    new Task(()=>results[0] = Sum(1000),TaskCreationOptions.AttachedToParent).Start();
                    new Task(()=>results[1] = Sum(1000),TaskCreationOptions.AttachedToParent).Start();
                    new Task(()=>results[2] = Sum(1000),TaskCreationOptions.AttachedToParent).Start();
                    return results;
                });
                var cwt = parent.ContinueWith(parentTask => Array.ForEach(parentTask.Result, 
                    Console.WriteLine));
                parent.Start();
            }
            public static void TestFactory()
            {
                Task parent = new Task(() =>
                {
                    var cts = new CancellationTokenSource();
                    var tf = new TaskFactory<int>(cts.Token,
                        TaskCreationOptions.AttachedToParent,
                        TaskContinuationOptions.ExecuteSynchronously,
                        TaskScheduler.Default);
                    var childTasks = new[]{
                        tf.StartNew(()=>Sum(cts.Token,1000)),
                        tf.StartNew(()=>Sum(cts.Token,2000)),
                        tf.StartNew(()=>Sum(cts.Token,int.MaxValue)),
                    };
                    tf.ContinueWhenAll(childTasks,
                        CompletedTasks => CompletedTasks.Where(t => !t.IsFaulted && !t.IsCanceled)
                            .Max(t => t.Result),
                        CancellationToken.None)
                        .ContinueWith(t => Console.WriteLine("the maximun is : " + t.Result),
                        TaskContinuationOptions.ExecuteSynchronously);
                });
                parent.ContinueWith(p =>
                {
                    StringBuilder sb = new StringBuilder("the following exception occurred: "
                        + Environment.NewLine);
                    foreach (var e in p.Exception.Flatten().InnerExceptions)
                    {
                        sb.AppendLine(" " + e.GetType().ToString());
                        Console.WriteLine(sb.ToString());
                    }
                }, TaskContinuationOptions.OnlyOnFaulted);
                parent.Start();
            }
        }
        internal static class TimerDemo 
        {
            private static Timer _timer;
            public static void Go()
            {
                Console.WriteLine("starting a timer");
                using (_timer = new Timer(ComputeBoundOp, 5, 0, Timeout.Infinite))
                {
                    Console.WriteLine("doing other work here");
                    Thread.Sleep(10000);
                }
            }
            private static void ComputeBoundOp(object state)
            {
                Console.WriteLine("state={0}", state);
                Thread.Sleep(1000);
                _timer.Change(2000, Timeout.Infinite);
            }
        }
  • 相关阅读:
    linux项目部署学习(1) pyhton3的虚拟环境virtualenv和virtualenvwrapper详解
    linux下pip查看安装包的路径、和指定安装目录
    python+selenium实现长截图
    selenium设置chrome浏览器保持登录方式两种options和cookie
    linux中离线安装django
    理解 bashrc 和 profile
    Django部署阿里云服务时候报错:SQLite 3.8.3 or later is required (found 3.7.17)
    Django的django-admin工具详解
    Yum Install --Downloadonly 离线下载依赖包研究
    分治法求n个点中的最近距离
  • 原文地址:https://www.cnblogs.com/ly7454/p/3655995.html
Copyright © 2020-2023  润新知