• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Semaphore类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Semaphore的典型用法代码示例。如果您正苦于以下问题:C# Semaphore类的具体用法?C# Semaphore怎么用?C# Semaphore使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Semaphore类属于命名空间,在下文中一共展示了Semaphore类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Barrier

 public Barrier(uint count)
 {
     threadCount = count;
     mutex = new Semaphore(1, 1);
     sem = new Semaphore(0, (int) count);
     sem2 = new Semaphore(0, (int)count);
 }
开发者ID:romanchom,项目名称:TSK2015,代码行数:7,代码来源:Barrier.cs


示例2: Run

    private int Run(int iCount, int mCount, string semName, int iRandom)
    {
        // Testing createdNew
        bool createdNew;
        int iRet = -1, count = iCount;
        Semaphore sem = null;
        if (iRandom > 0)
            semName = Common.GenerateUnicodeString(iRandom);
        try
        {
            using(sem = new Semaphore(iCount, mCount, semName, out createdNew))
            {
                if (iCount > 0)
                {
                    sem.WaitOne();
                    count--;
                }

                int iPrev = sem.Release();
                if (iPrev == count && createdNew)
                    iRet = 100;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Unexpected exception thrown:  " + ex.ToString());
        }

        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:31,代码来源:semaphorector4.cs


示例3: StartCore

        protected override void StartCore()
        {
            // initialize the requests counter with a dud count
              // as to not set the countdown event immediately
              _requestsCounter = new CountdownEvent(1);

              _stopSignal = new ManualResetEvent(false);
              _pumpCounter = new Semaphore(ConcurrentPumpCount, ConcurrentPumpCount);

              // initialize an http listener
              _listener = new HttpListener();

              foreach (var url in Urls)
            _listener.Prefixes.Add(url);

              // initialize and start the request pump
              _pumpThread = new Thread(_ => requestPump()) {
            IsBackground = false,
            Name = RequestPumpThreadName,
            Priority = ThreadPriority.AboveNormal
              };

              _listener.Start();
              _pumpThread.Start();
        }
开发者ID:chakrit,项目名称:plumber,代码行数:25,代码来源:HttpListenerServer.core.cs


示例4: Main

        public static void Main(string[] args)
        {
            _threadPool = new Semaphore(MaxThreads, MaxThreads);

              using (_s3Client = AWSClientFactory.CreateAmazonS3Client(ConfigurationManager.AppSettings["AWSAccessKey"], ConfigurationManager.AppSettings["AWSSecretKey"]))
              {
            for (int level = StartLevel; level <= EndLevel; ++level)
            {
              double tileSize = WebMercatorDelta * Math.Pow(2, 1 - level);

              int startRow = Convert.ToInt32(Math.Truncate((WebMercatorDelta - ExtentMaxY) / tileSize)) - TilePaddingY;
              int endRow = Convert.ToInt32(Math.Truncate((WebMercatorDelta - ExtentMinY) / tileSize)) + 1 + TilePaddingY;
              int startColumn = Convert.ToInt32(Math.Truncate((ExtentMinX + WebMercatorDelta) / tileSize)) - TilePaddingX;
              int endColumn = Convert.ToInt32(Math.Truncate((ExtentMaxX + WebMercatorDelta) / tileSize)) + 1 + TilePaddingX;

              for (int r = startRow; r <= endRow; ++r)
              {
            for (int c = startColumn; c <= endColumn; ++c)
            {
              _threadPool.WaitOne();

              Thread t = new Thread(new ParameterizedThreadStart(CopyImage));
              t.Start(new UserData(level, r, c));

              Console.Write(String.Format("{0}Level {1} Row {2} Column {3}", new String('\b', 40), level, r, c).PadRight(80));
            }
              }
            }
              }

              Console.WriteLine((new String('\b', 40) + "Done").PadRight(80));
              Console.Read();
        }
开发者ID:agrc,项目名称:tile-etl,代码行数:33,代码来源:EtlToS3.cs


示例5: Run

    private int Run()
    {
        int iRet = -1;
        string sName = Common.GetUniqueName();
        //  open a closed semaphore
        try
        {
            using (Semaphore sem1 = new Semaphore(10, 10, sName))
            {
            }
            Semaphore sem2 = Semaphore.OpenExisting(sName);
        }
        catch (WaitHandleCannotBeOpenedException)
        {
            //Expected	
            iRet = 100;
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught unexpected exception: " +
                e.ToString());
        }

        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:26,代码来源:semaphoreopenneg5.cs


示例6: Run

    private int Run()
    {
        int iRet = -1;
        string sName = Common.GetUniqueName();
        //  open a Mutex with the same name as a Semaphore
        using (Semaphore sem = new Semaphore(10, 10, sName))
        {
            try
            {
                Mutex mut = Mutex.OpenExisting(sName);
            }
            catch(WaitHandleCannotBeOpenedException)
            {
                //Expected	
                iRet = 100;
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught exception where WaitHandleCannotBeOpenedException was expected: " +
                    e.ToString());
            }
        }

        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:26,代码来源:openmutexneg6.cs


示例7: Run

    private int Run(int initalValue, int maxValue, string semName, int iRandom) 
    {
        int iRet = -1;
        Semaphore sem = null;
        if (iRandom > 0)
            semName = Common.GenerateUnicodeString(iRandom);
        try
        {
            using (sem = new Semaphore(initalValue, maxValue, semName))
            {
                Console.WriteLine("Semaphore was created!");
            }
        }
        catch(ArgumentException)
        {
            //  Expected
            iRet = 100;
        }
        catch(Exception e)
        {
            Console.WriteLine("Unexpected exception thrown: " + 
                e.ToString());
        }
 
        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:27,代码来源:semaphorectorneg2.cs


示例8: Downloader

        /// <summary>
        /// Initializes a new instance of <see cref="Downloader"/> with a configuration,
        /// allowing the given number of parallel downloads.
        /// </summary>
        /// <param name="parallelDownloads">The maximum number of parallel downloads.
        /// This value must be in the interval of <c>1</c> and <c>9999</c>.</param>
        public Downloader(int parallelDownloads)
        {
            if (parallelDownloads < 1 || parallelDownloads > 9999)
            {
                throw new ArgumentOutOfRangeException("parallelDownloads",
                    "The number of parallel downloads must be at least 1 and less than 10000.");
            }
            Debug.WriteLine("Initializing downloader for " + parallelDownloads + " parallel downloads.");
            UrlResolver = new List<IUrlResolver>();
            ParallelDownloads = parallelDownloads;
            webClients = new WebClient[parallelDownloads];
            downloadEvents = new AutoResetEvent[parallelDownloads];
            for (int i = 0; i < parallelDownloads; i++)
            {
                downloadEvents[i] = new AutoResetEvent(false);
            }
            availableTasks = new Semaphore(0, int.MaxValue);

            Debug.WriteLine("Starting worker threads...");
            for (int i = 0; i < parallelDownloads; i++)
            {
                var no = i;
                var t = new Thread(() => Worker(no));
                t.Name = string.Format("DownloadWorker_{0:00}", no);
                t.Priority = ThreadPriority.BelowNormal;
                t.Start();
            }
            DownloadAttempts = 1;
        }
开发者ID:mastersign,项目名称:bench,代码行数:35,代码来源:Downloader.cs


示例9: Server

 public Server(int port)
 {
     this.port = port;
     m_ServerSemaphore = new Semaphore(20,20);
     errorHandler = new ErrorPageHandler();
     ext = XMLParser.DeserializeExtensionXML();
 }
开发者ID:BioDice,项目名称:SEHACWebServer,代码行数:7,代码来源:Server.cs


示例10: Run

    private int Run(int iCount, int mCount)
    {
        // Testing basic scenario
        int iRet = -1;
        Semaphore sem = null;
        try
        {
            using (sem = new Semaphore(iCount, mCount))
            {
                int iPrev = 0, count = iCount;
                // Do a wait one if we can
                if (iCount > 0)
                {
                   sem.WaitOne();
                   count--;
                }
                iPrev = sem.Release();

                if (iPrev == count)
                   iRet = 100;
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("FAIL: CtorTest1(" + iCount + "," + mCount + ") - Unexpected exception thrown:  " + ex.ToString());
        }
        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:29,代码来源:semaphorector1.cs


示例11: Run

 private int Run(int initCount, int maxCount)
 {
     int iRet = -1;
     Semaphore sem = null;
     try
     {
         using (sem = new Semaphore(initCount, maxCount))
         {
             Console.WriteLine("Semaphore was created!");
         }
     }
     catch(ArgumentException)
     {
         //  Expected
         iRet = 100;
     }
     catch(Exception e)
     {
         //  other exceptions are not valid
         Console.WriteLine("Unexpected exception thrown:  " + 
             e.ToString());
     }
     Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
     return iRet;
 }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:25,代码来源:semaphorectorneg1.cs


示例12: WaitPanelThread

 public WaitPanelThread(Point origin, int delay, bool positiveAxis, bool horizontal, Panel panel, Plane plane, Semaphore semaphoreThis, Semaphore semaphoreNext, Semaphore semaphoreTerminal, Buffer bufferPrevious, Buffer bufferNext, Buffer bufferTerminal, int length, int terminalID)
 {
     this.origin = origin;
     this.delay = delay;
     this.positiveAxis = positiveAxis;
     this.panel = panel;
     this.plane = plane;
     this.panel.Paint += new PaintEventHandler(this.panel_Paint);
     if (horizontal)
     {
         this.xDelta = positiveAxis ? +10 : -10;
         this.yDelta = 0;
     }
     else
     {
         this.xDelta = 0;
         this.yDelta = positiveAxis ? +10 : -10;
     }
     this.semaphoreThis = semaphoreThis;
     this.semaphoreNext = semaphoreNext;
     this.semaphoreTerminal = semaphoreTerminal;
     this.bufferPrevious = bufferPrevious;
     this.bufferNext = bufferNext;
     this.bufferTerminal = bufferTerminal;
     this.length = length;
     this.terminalID = terminalID;
 }
开发者ID:kathrynaj7,项目名称:AirportThreadingExample,代码行数:27,代码来源:WaitPanelThread.cs


示例13: Fetch

        public WebSite Fetch(string url, int depth = 0)
        {
            var webSite = new WebSite();
            webSite.Domain = WebTools.DomainHelper.GetDomain(url);
            var pages = new List<WebPage>();
            webSite.Pages = pages;

            var queue = new ConcurrentQueue<FetchItem>();
            var visited = new HashSet<string>();

            queue.Enqueue(new FetchItem { Depth = 0, Url = url });

            Semaphore semaphore = new Semaphore(1, MaxThreads);
            FetchItem item;
            var mutex = new object();
            while (true)
            {
                lock(mutex)
                {
                    semaphore.WaitOne();
                    if (!queue.TryDequeue(out item))
                    {
                        break;
                    }

                    new Thread(() => FetchAndAdd(semaphore, item, depth, webSite.Domain, visited, queue, webSite.Pages)).Start();
                }
            }

            return webSite;
        }
开发者ID:trooper,项目名称:websiteclassification,代码行数:31,代码来源:Fetcher.cs


示例14: ServerStart

        private Socket _server; //服务器Socket监听对象

        #endregion Fields

        #region Constructors

        /// <summary>
        /// 初始化通信监听
        /// </summary>
        /// <param name="max">最大连接数</param>
        /// <param name="port">监听的端口</param>
        public ServerStart(int max,int port)
        {
            _server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            _maxClient = max;                               //实例化socket监听对象

            _pool=new UserTokenPool(max);                   //实例化连接池对象

            //实例化一个最大允许max个线程允许的信号量
            //并将它的计数器的初始值设为max
            //这就是说除了调用该信号量的线程都将被阻塞
            _acceptClients = new Semaphore(max,max);

            //初始化创建max个数的链接对象并存入连接池
            for (var i = 0; i < max; i++)
            {
                //初始化token信息
                var token=new UserToken();

                //绑定接收事件
                token.ReceiveSAEA.Completed+=
                    new EventHandler<SocketAsyncEventArgs>(IO_Comleted);

                //绑定发送事件
                token.SendSAEA.Completed+=
                    new EventHandler<SocketAsyncEventArgs>(IO_Comleted);

                token.LD = LD;
                token.LE = LE;
                token.encode = encode;
                token.decode = decode;
                token.sendProcess = ProccessSend;

                _pool.Push(token);
            }
        }
开发者ID:evesgf,项目名称:LOL-for-Unity,代码行数:46,代码来源:ServerStart.cs


示例15: Run

    private int Run(int iCount, int mCount, string semName, int iRandom)
    {
        // Testing basic string scenario
        int iRet = -1, count = iCount;
        Semaphore sem1 = null, sem2 = null;
        if (iRandom > 0)
            semName = Common.GenerateUnicodeString(iRandom);
        try
        {
            using (sem1 = new Semaphore(iCount, mCount, semName))
            {
                using (sem2 = (semName != null && semName != string.Empty) ? Semaphore.OpenExisting(semName) : sem1)
                {
                    if (iCount > 0)
                    {
                        sem2.WaitOne();
                        count--;
                    }

                    int iPrev = sem2.Release();

                    if (iPrev == count)
                        iRet = 100;
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("Unexpected exception thrown:  " + ex.ToString());
        }
        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:33,代码来源:semaphorector2.cs


示例16: TVDoc

                                         }; // TODO: move into settings, and allow user to edit these

        #endregion Fields

        #region Constructors

        public TVDoc(FileInfo settingsFile, TheTVDB tvdb, CommandLineArgs args)
        {
            this.mTVDB = tvdb;
            this.Args = args;

            this.Ignore = new List<IgnoreItem>();

            this.Workers = null;
            this.WorkerSemaphore = null;

            this.mStats = new TVRenameStats();
            this.mDirty = false;
            this.TheActionList = new ItemList();

            this.Settings = new TVSettings();

            this.MonitorFolders = new List<String>();
            this.IgnoreFolders = new List<String>();
            this.SearchFolders = new List<String>();

            ShowItems = new List<ShowItem>();
            this.AddItems = new FolderMonitorEntryList();

            this.DownloadDone = true;
            this.DownloadOK = true;

            this.ActionCancel = false;
            this.ScanProgDlg = null;

            this.LoadOK = ((settingsFile == null) || this.LoadXMLSettings(settingsFile)) && this.mTVDB.LoadOK;

            UpdateTVDBLanguage();

            //    StartServer();
        }
开发者ID:mudboy,项目名称:tvrename,代码行数:41,代码来源:TVDoc.cs


示例17: EventManager

 /// <summary>
 /// No-parameter constructor. Sets the semaphores and starts "Semaphore administrator" thread.
 /// </summary>
 private EventManager()
 {
     token = new Semaphore(1, 1);
     gotToken = new Semaphore(0, 1);
     tokenAdmin = new Thread(new ThreadStart(administrateToken));
     tokenAdmin.Start();
 }
开发者ID:yonglehou,项目名称:EventManager_CSharp_WCF,代码行数:10,代码来源:EventManager.cs


示例18: HttpServer

        public HttpServer(int maxAccept, int maxConnections, int bufferSize)
        {
            timeoutTimer = new System.Timers.Timer(Timeout);
            timeoutTimer.Elapsed += timeoutTimer_Elapsed;
            this.maxAccept = maxAccept;
            this.maxConnections = maxConnections;
            this.bufferSize = bufferSize;
            this.enforceMaxClients = new Semaphore (maxConnections, maxConnections);
            this.bufferManager = BufferManager.CreateBufferManager (maxConnections, maxConnections * bufferSize * 2);

            for (int i = 0; i < maxAccept; i++) {
                var acceptArgs = new SocketAsyncEventArgs ();
                acceptArgs.Completed += HandleAcceptCompleted;
                this.acceptPool.Push (acceptArgs);
            }

            for (int i = 0; i < maxConnections; i++) {
                var readWriteArgs = new SocketAsyncEventArgs ();
                var client = new HttpClient ();
                readWriteArgs.UserToken = client;
                readWriteArgs.SetBuffer (this.bufferManager.TakeBuffer (bufferSize), 0, bufferSize);
                readWriteArgs.Completed += HandleReadWriteCompleted;
                this.readWritePool.Push (readWriteArgs);
            }

            timeoutTimer.Start();
        }
开发者ID:jacoblusk,项目名称:SAEA-HTTPD,代码行数:27,代码来源:HttpServer.cs


示例19: StartUDPListener

 public void StartUDPListener()
 {
     userSemaphore = new Semaphore(1, 1);
     Thread receivingThread = new Thread(messageReceiver);
     receivingThread.Start();
     SetTimer();
 }
开发者ID:Ikthios,项目名称:Communication-System,代码行数:7,代码来源:activeUserListener.cs


示例20: BruteForceThreadPool

        /// <summary>Initialize the thread pool.</summary>
        public BruteForceThreadPool(int maxWorker)
        {
            // Create our thread stores; we handle synchronization ourself
            // as we may run into situtations where multiple operations need to be atomic.
            // We keep track of the threads we've created just for good measure; not actually
            // needed for any core functionality.
            _waitingCallbacks = new Queue();
            _workerThreads = new ArrayList();
            _maxWorkerThreads = maxWorker;
            _inUseThreads = 0;

            // Create our "thread needed" event
            _workerThreadNeeded = new Semaphore(0);

            // Create all of the worker threads
            for (int i = 0; i < _maxWorkerThreads; i++)
            {
                // Create a new thread and add it to the list of threads.
                System.Threading.Thread newThread = new System.Threading.Thread(new ThreadStart(ProcessQueuedItems));
                _workerThreads.Add(newThread);

                // Configure the new thread and start it
                newThread.Name = "ManagedPoolThread #" + i.ToString();
                newThread.IsBackground = true;
                newThread.Start();
            }
        }
开发者ID:eduncan911,项目名称:dbrampup,代码行数:28,代码来源:ThreadPool.cs



注:本文中的Semaphore类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# SendCodeViewModel类代码示例发布时间:2022-05-24
下一篇:
C# SemanticVersion类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap