• 为什么有的人把代码写的如此复杂?


    技术群里有人发了一段代码:在这里插入图片描述
    附言:兄弟们,这个单例怎么样?

    我回复:什么鬼,看不懂啊?!

    也有其他小伙伴表示看不懂,看来大家的C#基础和我一样并不全面。

    我看不懂,主要是因为我没用过TaskCompletionSource和Interlocked的CompareExchange方法,然后经过我1、2个小时的研究,终于勉强看懂了。

    由于上面这段代码只贴了一张图,我没有拿到源码,所以我写了个差不多的Demo用于测试,代码如下:

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;

    namespace SingletonTest
    {
    public class Singleton
    {
    private static Task _stringTask;

        /// 
        /// 重置,方便重复测试
        /// 
        public void Reset()
        {
            _stringTask = null;
        }
    
        public Task InitAsync()
        {
            if (_stringTask != null)
            {
                return _stringTask;
            }
    
            var inition = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
    
            var initonTask = Interlocked.CompareExchange(ref _stringTask, inition.Task, null);
    
            if (initonTask != null)
            {
                return initonTask;
            }
    
            _stringTask = CreateContent(inition);
            return inition.Task;
        }
    
        private async Task CreateContent(TaskCompletionSource inition)
        {
            string content = await TextUtil.GetTextAsync();
            inition.SetResult(content);
            return content;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    }
    复制代码
    然后按照我自己的习惯,又写了一版:

    复制代码
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;

    namespace SingletonTest
    {
    class Singleton2
    {
    private static string _value;
    private SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1);

        /// 
        /// 重置,方便重复测试
        /// 
        public void Reset()
        {
            _value = null;
        }
    
        public async Task InitAsync()
        {
            if (_value != null)
            {
                return _value;
            }
    
            await _semaphoreSlim.WaitAsync();
            if (_value == null)
            {
                _value = await TextUtil.GetTextAsync();
            }
            _semaphoreSlim.Release();
    
            return _value;
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26

    }
    复制代码
    很容易懂,不是吗?

    这段代码我好像是理解了,可是我不理解的是,为什么代码会写的这么复杂呢?

    最主要的是我不理解下面几行:

    复制代码
    var inition = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);

    var initonTask = Interlocked.CompareExchange(ref _stringTask, inition.Task, null);

    if (initonTask != null)
    {
    return initonTask;
    }
    复制代码
    我要给它翻译成我能理解的代码,我意思到new的TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)也是个单例,所以我先写了个TaskCompletionSourceFactory类:

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;

    namespace SingletonTest
    {
    public class TaskCompletionSourceFactory : IDisposable
    {
    private TaskCompletionSource _value;

        private TaskCompletionSourceData _data;
    
        private SemaphoreSlim _semaphoreSlim = new SemaphoreSlim(1, 1);
    
        public TaskCompletionSourceData Instance
        {
            get
            {
                _semaphoreSlim.Wait();
                if (_value == null)
                {
                    _data = new TaskCompletionSourceData();
                    _value = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
                    _data.Value = _value;
                    _data.First = true;
                }
                else
                {
                    _data = new TaskCompletionSourceData();
                    _data.Value = _value;
                    _data.First = false;
                }
                _semaphoreSlim.Release();
                return _data;
            }
        }
    
        public void Dispose()
        {
            _semaphoreSlim.Dispose();
        }
    }
    
    public class TaskCompletionSourceData
    {
        public bool First { get; set; }
    
        public TaskCompletionSource Value { get; set; }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39

    }
    复制代码
    然后把Demo中Singleton这个类改写了一下:

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;

    namespace SingletonTest
    {
    public class Singleton3
    {
    private static Task _stringTask;

        /// 
        /// 重置,方便重复测试
        /// 
        public void Reset()
        {
            _stringTask = null;
        }
    
        public Task InitAsync(TaskCompletionSourceFactory factory)
        {
            if (_stringTask != null)
            {
                return _stringTask;
            }
    
            var inition = factory.Instance;
            if (!inition.First)
            {
                return inition.Value.Task;
            }
    
            _stringTask = CreateContent(inition.Value);
            return inition.Value.Task;
        }
    
        private async Task CreateContent(TaskCompletionSource inition)
        {
            string content = await TextUtil.GetTextAsync();
            inition.SetResult(content);
            return content;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    }
    复制代码
    当我差不多理解了之后,我发现原始代码有一点点小问题,就是TaskCompletionSource是有机率被重复new的。

    大家觉得哪种写法好呢?

    附:

    TextUtil.cs代码,是一个模拟获取文本的方法:

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;

    namespace SingletonTest
    {
    public class TextUtil
    {
    public static Task GetTextAsync()
    {
    return Task.Run(() =>
    {
    Thread.Sleep(10);
    Random rnd = new Random();
    return rnd.Next(0, 1000).ToString().PadRight(10);
    });
    }
    }
    }
    复制代码
    测试代码:

    复制代码
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;

    namespace SingletonTest
    {
    class Program
    {
    private static int _count = 200;
    private static Singleton _singleton = new Singleton();
    private static Singleton2 _singleton2 = new Singleton2();
    private static Singleton3 _singleton3 = new Singleton3();

        static void Main(string[] args)
        {
            ThreadPool.SetMinThreads(20, 20);
            Task.Run(() => { }); //Task预热
            Console.WriteLine("输入1测试Singleton,输入2测试Singleton2,如果值都相同,说明单例测试通过,否则不通过");
    
            while (true)
            {
                var key = Console.ReadKey().Key;
    
                if (key == ConsoleKey.D1)
                {
                    Console.WriteLine("测试Singleton");
                    Test();
                }
    
                if (key == ConsoleKey.D2)
                {
                    Console.WriteLine("测试Singleton2");
                    Test2();
                }
    
                if (key == ConsoleKey.D3)
                {
                    Console.WriteLine("测试Singleton3");
                    Test3();
                }
            }
    
        }
    
        public static void Test()
        {
            List taskList = new List();
            for (int i = 0; i < _count; i++)
            {
                Task task = Task.Run(async () =>
                {
                    string content = await _singleton.InitAsync();
                    Console.Write(content);
                });
                taskList.Add(task);
            }
    
            Task.WaitAll(taskList.ToArray());
            _singleton.Reset();
            Console.WriteLine("");
        }
    
        public static void Test2()
        {
            List taskList = new List();
            for (int i = 0; i < _count; i++)
            {
                Task task = Task.Run(async () =>
                {
                    string content = await _singleton2.InitAsync();
                    Console.Write(content);
                });
                taskList.Add(task);
            }
    
            Task.WaitAll(taskList.ToArray());
            _singleton2.Reset();
            Console.WriteLine("");
        }
    
        public static void Test3()
        {
            TaskCompletionSourceFactory factory = new TaskCompletionSourceFactory();
            List taskList = new List();
            for (int i = 0; i < _count; i++)
            {
                Task task = Task.Run(async () =>
                {
                    string content = await _singleton3.InitAsync(factory);
                    Console.Write(content);
                });
                taskList.Add(task);
            }
    
            Task.WaitAll(taskList.ToArray());
            _singleton3.Reset();
            factory.Dispose();
            Console.WriteLine("");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87

    }

  • 相关阅读:
    P1541 [NOIP2010 提高组] 乌龟棋(4维背包问题)
    【C++】C 语言 和 C++ 语言中 const 关键字分析 ( const 关键字左数右指原则 | C 语言中常量的原理和缺陷 | C++ 语言中常量原理 - 符号表存储常量 )
    实习记录--(海量数据如何判重?)--每天都要保持学习状态和专注的状态啊!!!---你的未来值得你去奋斗
    「学习笔记」记忆化搜索
    今年的秋招面试,确实有点难。
    createNodeIterator使用+元素替换
    JQuery操作
    计算机程序设计-第3周(循环结构)
    C++ 学习之路(待更新)
    提交数据加快百度搜索引擎收录
  • 原文地址:https://blog.csdn.net/weixin_43214644/article/details/125938810