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

C# Threading.SemaphoreSlim类代码示例

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

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



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

示例1: ExtremeDisposal

        public void ExtremeDisposal()
        {
            using (var context = CreateContext())
            {
                Assert.AreEqual(-1, context.Publisher.MySettings.MaxConnectionRetry, "For this test, we want the worst situation");

                context.Publisher.Start(0);
                Assert.IsTrue(context.Publisher.Started);

                var message = new byte[] { 0, 1, 1 };
                var connectionFail = new SemaphoreSlim(0);
                context.Model.Setup(m => m.BasicPublish(It.IsAny<string>(), It.IsAny<string>(), context.Publisher.Props, message)).Throws(new Exception("I don't want your message anymore"));
                context.Connection.Setup(c => c.CreateModel()).Callback(() => connectionFail.Release(1)).Throws(new Exception("And I don't want to accept your connection either"));

                context.Publisher.Publish("test", message);

                /* The way callbacks are implemented on exception throwing mocks does not garantee
                 * that the callback is called "after" the exception is thrown.
                 * If we wait for two, we are sure at least one has been finished !
                 */
                Assert.IsTrue(connectionFail.Wait(1000));
                Assert.IsTrue(connectionFail.Wait(1000));

                context.Publisher.Dispose();
                context.Publisher = null; //to avoid the double dispose of Publisher
                //The real test here is that eventually the Dispose method returns
                Assert.Pass();
            }
        }
开发者ID:RonKillerMan,项目名称:RabbitMQHare,代码行数:29,代码来源:RabbitPublisher.cs


示例2: TestCancelWaitAsyncInternal

        private async Task TestCancelWaitAsyncInternal()
        {
            var r = new Random();
            var s = new SemaphoreSlim(1);

            await Task.WhenAll(Enumerable.Range(0, 100).Select(async i =>
            {
                var ct = CancellationToken.None;
                if ((i % 5) == 0)
                {
                    var cts = new CancellationTokenSource();
                    var t = Task.Delay(1).ContinueWith(_ => cts.Cancel());
                    ct = cts.Token;
                }

                try
                {
                    await s.WaitAsync(ct);
                    await Delay(r, ct).ConfigureAwait(false);
                }
                catch (TestException) { }
                catch (OperationCanceledException) { }
                finally
                {
                    s.Release();
                }
            }));
        }
开发者ID:KKubodera,项目名称:MinimumAsyncBridge,代码行数:28,代码来源:UnitTestSemaphoreSlim.cs


示例3: GetWithRetryAsync

		public static async Task<HttpResponseMessage> GetWithRetryAsync(this HttpClient client, string url, SemaphoreSlim semaphore, params int[] retryDelay)
		{
			if (retryDelay.Any(delay => delay <= 0))
			{
				throw new ArgumentException("Delay should be greate than 0.", nameof(retryDelay));
			}

			await semaphore.WaitAsync();
			try
			{
				int retryCount = 0;
				while (true)
				{
					try
					{
						return await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
					}
					catch (TaskCanceledException)
					{
						if (retryCount >= retryDelay.Length)
						{
							throw;
						}
					}
					await Task.Delay(retryDelay[retryCount]);
					retryCount++;
				}
			}
			finally
			{
				semaphore.Release();
			}
		}
开发者ID:zhangz,项目名称:Toolbox,代码行数:33,代码来源:HttpClientExtensions.cs


示例4: DiskCache

		/// <summary>
		/// Initializes a new instance of the <see cref="FFImageLoading.Cache.DiskCache"/> class.
		/// </summary>
		/// <param name="basePath">Base path.</param>
		/// <param name="version">Version.</param>
        public DiskCache(string basePath, string version)
        {
            // Can't use minilogger here, we would have too many dependencies
            System.Diagnostics.Debug.WriteLine("DiskCache path: " + basePath);

            this.basePath = basePath;

            if (!Directory.Exists(basePath))
                Directory.CreateDirectory(basePath);
			
            this.journalPath = Path.Combine(basePath, JournalFileName);
            this.version = version;
			this.lockJournal = new object();
			this.fileWriteLock = new SemaphoreSlim(initialCount: 1);
			this.fileWritePendingTasks = new ConcurrentDictionary<string, byte>();

            try 
			{
                InitializeWithJournal ();
            } 
			catch 
			{
                Directory.Delete (basePath, true);
                Directory.CreateDirectory (basePath);
            }

            ThreadPool.QueueUserWorkItem(CleanCallback);
        }
开发者ID:Sohojoe,项目名称:FFImageLoading,代码行数:33,代码来源:DiskCache.cs


示例5: ExclusiveTask

        private async Task ExclusiveTask(SemaphoreSlim s, Integer count, int seed, int iteration, bool due)
        {
            var r = new Random(seed);

            if (due)
            {
                try
                {
                    await Delay(r).ConfigureAwait(false);
                }
                catch { }
            }

            for (int i = 0; i < iteration; i++)
            {
                int localCount = 0;
                try
                {
                    await s.WaitAsync();
                    localCount = count.Value;
                    await Delay(r).ConfigureAwait(false);
                }
                catch (TestException) { }
                finally
                {
                    count.Value = localCount + 1;
                    s.Release();
                }
            }
        }
开发者ID:ch896,项目名称:MinimumAsyncBridge,代码行数:30,代码来源:UnitTestSemaphoreSlim.cs


示例6: Main

        static void Main(string[] args)
        {
            // initialize the semaphores
            semA = new SemaphoreSlim(2);
            semB = new SemaphoreSlim(2);

            // define the number of tasks we will use
            int taskCount = 10;

            // initialize the barrier
            cdEvent = new CountdownEvent(taskCount);

            Task[] tasks = new Task[10];
            for (int i = 0; i < taskCount; i++) {
                tasks[i] = Task.Factory.StartNew((stateObject) => {
                    InitialMethod((int)stateObject);
                    Console.WriteLine("Task {0} completed", Task.CurrentId);
                }, i);
            }

            // wait for all of the tasks to have reached a terminal method
            cdEvent.Wait();

            // throw an exception to force the debugger to break
            throw new Exception();
        }
开发者ID:clp-takekawa,项目名称:codes-from-books,代码行数:26,代码来源:Listing_04.cs


示例7: ServiceContext

        private ServiceContext()
        {
            _Slots = new List<ServiceSlot>();

            _StartSemaphore = new SemaphoreSlim(0);
            _StopSemaphore = new SemaphoreSlim(0);
        }
开发者ID:JackFong,项目名称:ServiceStarter,代码行数:7,代码来源:ServiceContext.cs


示例8: ConcurrentRunner

 public ConcurrentRunner(int maxThread, int loopEach, AutoResetEvent signal = null)
 {
     this.maxThread = maxThread;
     this.loopEach = loopEach;
     this.semaphore = new SemaphoreSlim(0, maxThread);
     this.signal = signal;
 }
开发者ID:zesus19,项目名称:c5.v1,代码行数:7,代码来源:ConcurrentRunner.cs


示例9: Consume

        // WIP, not producing useful numbers yet. Assumes one partition.
        public static async Task<long> Consume(string broker, string topic)
        {
            long n = 0;

            var topicConfig = new TopicConfig();
            topicConfig["auto.offset.reset"] = "smallest";
            var config = new Config()
            {
                GroupId = "benchmark-consumer",
                DefaultTopicConfig = topicConfig
            };
            using (var consumer = new EventConsumer(config, broker))
            {
                var signal = new SemaphoreSlim(0, 1);

                consumer.OnMessage += (obj, msg) =>
                {
                    n += 1;
                };

                consumer.OnEndReached += (obj, end) =>
                {
                    Console.WriteLine($"End reached");
                    signal.Release();
                };

                consumer.Subscribe(new List<string>{topic});
                consumer.Start();

                await signal.WaitAsync();
                Console.WriteLine($"Shutting down");
            }

            return n;
        }
开发者ID:yousifh,项目名称:rdkafka-dotnet,代码行数:36,代码来源:Program.cs


示例10: Authorize

        public async Task<TokenPair> Authorize(string clientId, string clientSecret, IEnumerable<string> scopes)
        {
            string uri = string.Format("/LoginPage.xaml?authEndpoint={0}&clientId={1}&scope={2}",
                                       authEndpoint,
                                       clientId,
                                       string.Join(" ", scopes));

            SemaphoreSlim semaphore = new SemaphoreSlim(0, 1);

            Observable.FromEvent<NavigatingCancelEventHandler, NavigatingCancelEventArgs>(
                h => new NavigatingCancelEventHandler(h),
                h => this.frame.Navigating += h,
                h => this.frame.Navigating -= h)
                      .SkipWhile(h => h.EventArgs.NavigationMode != NavigationMode.Back)
                      .Take(1)
                      .Subscribe(e => semaphore.Release());

            frame.Navigate(new Uri(uri, UriKind.Relative));

            await semaphore.WaitAsync();

            string authorizationCode = (string)PhoneApplicationService.Current.State["OAuth_Demo.AuthorizationCode"];

            return await RequestAccessToken(authorizationCode, clientId, clientSecret);
        }
开发者ID:praveenmohanmm,项目名称:PurposeColor_Bkp_Code,代码行数:25,代码来源:OAuthAuthorization.cs


示例11: AcquireAuthorizationAsync

 public async Task<AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, IDictionary<string, string> additionalHeaders, CallState callState)
 {
     returnedUriReady = new SemaphoreSlim(0);
     Authenticate(authorizationUri, redirectUri, additionalHeaders, callState);
     await returnedUriReady.WaitAsync().ConfigureAwait(false);
     return authorizationResult;
 }
开发者ID:AzureAD,项目名称:microsoft-authentication-library-for-dotnet,代码行数:7,代码来源:WebUI.cs


示例12: BaseClient

 /// <summary>
 /// Initialises a new instance of the <see cref="BaseClient"/> class.
 /// </summary>
 /// <param name="byteStream">The byte stream.</param>
 /// <param name="token">The token.</param>
 protected BaseClient(IByteStream byteStream, CancellationToken token)
 {
   this.ByteStream = byteStream;
   this.SendRateLimit = new SemaphoreSlim(1);
   this.InternalCancellation = new CancellationTokenSource();
   token.Register(() => this.InternalCancellation.Cancel());
 }
开发者ID:fireball87,项目名称:Telnet,代码行数:12,代码来源:BaseClientCancellable.cs


示例13: AwaitingConnectedSpheroRunner

 public AwaitingConnectedSpheroRunner(IStreamSocketWrapper streamSpheroWrapper)
 {
     _streamSpheroWrapper = streamSpheroWrapper;
     _itemsToSendEvent = new SemaphoreSlim(1);
     _itemsToSendEvent.Wait();
     _commandsToSend = new Queue<CommandWithActions>();
 }
开发者ID:jihlee,项目名称:BallControl,代码行数:7,代码来源:AwaitingConnectedSpheroRunner.cs


示例14: TaskMain

 static void TaskMain(SemaphoreSlim semaphore)
 {
     bool isCompleted = false;
       while (!isCompleted)
       {
     if (semaphore.Wait(600))
     {
       try
       {
     Console.WriteLine("Task {0} locks the semaphore", Task.CurrentId);
     Thread.Sleep(2000);
       }
       finally
       {
     Console.WriteLine("Task {0} releases the semaphore", Task.CurrentId);
     semaphore.Release();
     isCompleted = true;
       }
     }
     else
     {
       Console.WriteLine("Timeout for task {0}; wait again",
      Task.CurrentId);
     }
       }
 }
开发者ID:CNinnovation,项目名称:ParallelProgrammingFeb2016,代码行数:26,代码来源:Program.cs


示例15: BufferStream

 internal BufferStream()
 {
     _readLock = new SemaphoreSlim(1, 1);
     _writeLock = new SemaphoreSlim(1, 1);
     _bufferedData = new ConcurrentQueue<byte[]>();
     _readWaitingForData = new TaskCompletionSource<object>();
 }
开发者ID:prepare,项目名称:WebSockets,代码行数:7,代码来源:BufferStream.cs


示例16: QueueProcessor

 public QueueProcessor(int maxConcurrentJobs, JobQueue jobQueue)
 {
     _semaphore = new SemaphoreSlim(maxConcurrentJobs);
     _jobQueue = jobQueue;
     Task.Factory.StartNew(TaskStartLoop, _cancellationTokenSource.Token);
     _jobQueue.JobAdded += JobQueueOnJobAdded;
 }
开发者ID:VictorGavrish,项目名称:MentoringD2D3,代码行数:7,代码来源:QueueProcessor.cs


示例17: HttpNegotiationQueue

        public HttpNegotiationQueue(WebSocketFactoryCollection standards, WebSocketConnectionExtensionCollection extensions, WebSocketListenerOptions options)
        {
            Guard.ParameterCannotBeNull(standards, "standards");
            Guard.ParameterCannotBeNull(extensions, "extensions");
            Guard.ParameterCannotBeNull(options, "options");

            _options = options;
            _extensions = extensions;
            _cancel = new CancellationTokenSource();
            _semaphore = new SemaphoreSlim(options.ParallelNegotiations);
            
            _sockets = new BufferBlock<Socket>(new DataflowBlockOptions()
            {
                BoundedCapacity = options.NegotiationQueueCapacity,
                CancellationToken = _cancel.Token
            });

            _negotiations = new BufferBlock<WebSocketNegotiationResult>(new DataflowBlockOptions()
            {
                BoundedCapacity = options.NegotiationQueueCapacity,
                CancellationToken = _cancel.Token,
            });

            _cancel.Token.Register(_sockets.Complete);
            _cancel.Token.Register(_negotiations.Complete);

            _handShaker = new WebSocketHandshaker(standards, _options);

            Task.Run((Func<Task>)WorkAsync);
        }
开发者ID:papci,项目名称:WebSocketListener,代码行数:30,代码来源:HttpNegotiationQueue.cs


示例18: EnsureList

        /// <summary>
        /// Ensures the list.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="file">The file.</param>
        /// <param name="httpClient">The HTTP client.</param>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="semaphore">The semaphore.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public static async Task EnsureList(string url, string file, IHttpClient httpClient, IFileSystem fileSystem, SemaphoreSlim semaphore, CancellationToken cancellationToken)
        {
            var fileInfo = fileSystem.GetFileInfo(file);

            if (!fileInfo.Exists || (DateTime.UtcNow - fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays > 1)
            {
                await semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

                try
                {
                    var temp = await httpClient.GetTempFile(new HttpRequestOptions
                    {
                        CancellationToken = cancellationToken,
                        Progress = new Progress<double>(),
                        Url = url

                    }).ConfigureAwait(false);

					fileSystem.CreateDirectory(Path.GetDirectoryName(file));

					fileSystem.CopyFile(temp, file, true);
                }
                finally
                {
                    semaphore.Release();
                }
            }
        }
开发者ID:paul-777,项目名称:Emby,代码行数:38,代码来源:ImageUtils.cs


示例19: Main

    static int Main(string[] args)
    {
        SemaphoreSlim s = new SemaphoreSlim(initialCount: 1);

        var cts = new CancellationTokenSource();
        s.Wait();
        var t = s.WaitAsync(cts.Token);
        s.Release();
        cts.Cancel();


        if (t.Status != TaskStatus.Canceled && s.CurrentCount == 0)
        {
            Console.WriteLine("PASS");
            return 100;
        }
        else
        {
            Console.WriteLine("FAIL");
            Console.WriteLine("Expected task status to not be Canceled and s.CurrentCount == 0");
            Console.WriteLine("Actual: Task: " + t.Status + "; CurrentCount: " + s.CurrentCount);
            return 101;
        }


    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:26,代码来源:test489437.cs


示例20: Producer

 /// <summary>
 /// Construct a Producer class.
 /// </summary>
 /// <param name="brokerRouter">The router used to direct produced messages to the correct partition.</param>
 /// <param name="maximumAsyncQueue">The maximum async calls allowed before blocking new requests.  -1 indicates unlimited.</param>
 /// <remarks>
 /// The maximumAsyncQueue parameter provides a mechanism for blocking an async request return if the amount of requests queue is 
 /// over a certain limit.  This is usefull if a client is trying to push a large stream of documents through the producer and
 /// wants to block downstream if the producer is overloaded.
 /// 
 /// A message will start its timeout countdown as soon as it is added to the producer async queue.  If there are a large number of 
 /// messages sitting in the async queue then a message may spend its entire timeout cycle waiting in this queue and never getting
 /// attempted to send to Kafka before a timeout exception is thrown.
 /// </remarks>
 public Producer(IBrokerRouter brokerRouter, int maximumAsyncQueue = -1)
 {
     _router = brokerRouter;
     _metadataQueries = new MetadataQueries(_router);
     _maximumAsyncQueue = maximumAsyncQueue == -1 ? int.MaxValue : maximumAsyncQueue;
     _sendSemaphore = new SemaphoreSlim(_maximumAsyncQueue, _maximumAsyncQueue);
 }
开发者ID:thetechi,项目名称:misakai-kafka,代码行数:21,代码来源:Producer.cs



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C# Threading.SpinWait类代码示例发布时间:2022-05-26
下一篇:
C# Threading.Semaphore类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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