net 多线程学习 27 自旋锁 SpinLock


using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;


namespace SpinLockDemo
{
    class Program
    {
		    //等待直至可用
        public static SpinLock spinLock = new SpinLock();

        static void Main(string[] args)
        {
            //比如开启5个task
            for (int i = 0; i < 5; i++)
            {
                Task.Factory.StartNew(() =>
                {
                    Run();
                });
            }

            Console.Read();
        }

        static int nums = 0;

        static void Run()
        {
            for (int i = 0; i < 100; i++)
            {
                try
                {
                    var b = false;

                    spinLock.Enter(ref b);

                    Console.WriteLine(nums++);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    spinLock.Exit();
                }
            }
        }
    }
}



作者:spike

分类: Net

创作时间:2023-06-25

更新时间:2024-12-09

联系方式放在中括号之中例如[[email protected]],回复评论在开头加上标号例如:#1