当前位置: 首页>>代码示例>>C#>>正文


C# Threading.SemaphoreSlim类代码示例

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


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


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