static void Main(string[] args) { IExecutorService executorService = Executors.NewFixedThreadPool(THREAD_POOL_SIZE); for (int i = 0; i < 100; i++) { SumNumbers sumNumbers = new SumNumbers(10000000 + i); executorService.Execute(sumNumbers.CalculateSum); } for (int i = 0; i < 100; i++) { SumNumbers2 sumNumbers2 = new SumNumbers2(); executorService.Execute(() => sumNumbers2.CalculateSumWithArgs(100)); } // This will make the executor accept no new threads // and finish all existing threads in the queue executorService.Shutdown(); // Wait until all threads are finish while (!executorService.IsTerminated) { } Console.WriteLine("Finished all threads. Hit enter to exit"); Console.ReadLine(); }
/// <summary> /// Adds the action to the end of the queue. /// </summary> public void AddToQueueOrExecute(Func <Task> runnable) { lock (_gate) { if (_queueing) { _runnableList.AddLast(runnable); } else { _executor.Execute(runnable); } } }
private async void ConnectToHubRoom() { try { State = ConnectionState.New; //TODO: Call SignalR Hub Connect To Room; This returns The relevant Room Parameters and potential errors if available. //await App.HubConnection.StartAsync(); var str = await App.HubConnection.InvokeAsync <string>("GetRoomParametersAsync", roomConnectionParameters.RoomId, roomConnectionParameters.IsInitator, "https://global.xirsys.net/_turn/DemoWebRTC"); var roomSObject = JObject.Parse(str); var roomParams = roomSObject.ToObject <RoomParameterResponse>(); var _roomSignalingParameters = new SignalingParameters { IsInitiator = roomParams.IsInitiator, ClientId = roomParams.ClientId, IceServers = roomParams.IceServers, IceCandidates = roomParams.IceCandidates, OfferSdp = roomParams.OfferSdp }; executor.Execute(() => { SignalingParametersReady(_roomSignalingParameters); }); } catch (Exception ex) { ReportError($"ERROR {ex.Message}"); return; } }
/// <summary> /// Associates encodedImage with given key in disk cache. /// Disk write is performed on background thread, so the /// caller of this method is not blocked. /// </summary> public Task Put(ICacheKey key, EncodedImage encodedImage) { Preconditions.CheckNotNull(key); Preconditions.CheckArgument(EncodedImage.IsValid(encodedImage)); // Store encodedImage in staging area _stagingArea.Put(key, encodedImage); // Write to disk cache. This will be executed on background thread, // so increment the ref count. When this write completes // (with success/failure), then we will bump down the ref count again. EncodedImage finalEncodedImage = EncodedImage.CloneOrNull(encodedImage); try { Task writeTask = _writeExecutor.Execute(() => { try { WriteToDiskCache(key, finalEncodedImage); } finally { _stagingArea.Remove(key, finalEncodedImage); EncodedImage.CloseSafely(finalEncodedImage); // Removes write task after it's completed. Task writeTaskCompleted = default(Task); _writeToDiskCacheTasks.TryRemove(key, out writeTaskCompleted); } }); _writeToDiskCacheTasks.TryAdd(key, writeTask); return(writeTask); } catch (Exception) { // We failed to enqueue cache write. Log failure and decrement ref count // TODO: 3697790 Debug.WriteLine($"Failed to schedule disk-cache write for { key.ToString() }"); _stagingArea.Remove(key, encodedImage); EncodedImage.CloseSafely(finalEncodedImage); // Removes write task due to error. Task writeTaskCompleted = default(Task); _writeToDiskCacheTasks.TryRemove(key, out writeTaskCompleted); throw; } }
internal Task FetchASync( FetchState fetchState, INetworkFetcherCallback callback, CancellationToken token) { return(_executorService.Execute( async() => { try { using (var response = await DownloadFrom(fetchState.Uri, MAX_REDIRECTS, token).ConfigureAwait(false)) { if (response != null) { using (var inputStream = await response.Content.ReadAsInputStreamAsync().AsTask().ConfigureAwait(false)) using (var stream = inputStream.AsStreamForRead()) { callback.OnResponse(stream, -1); } } } } catch (Exception e) { callback.OnFailure(e); } }) .Result); }
private void AssertExecutorDropsTaskOnShutdown(IExecutorService executor) { var runnable = MockRepository.GenerateStub <IRunnable>(); executor.Shutdown(); executor.Execute(runnable); JoinPool(executor); runnable.AssertWasNotCalled(r => r.Run()); }
/// <summary> /// Notifies progress update. /// </summary> protected void NotifyProgressUpdate() { foreach (var pair in _subscribers) { IDataSubscriber <T> subscriber = pair.Item1; IExecutorService executor = pair.Item2; executor.Execute(() => { subscriber.OnProgressUpdate(this); }); } }
/// <summary> /// Creates a bitmap from encoded bytes. /// Supports JPEG but callers should use DecodeJPEGFromEncodedImage /// for partial JPEGs. /// </summary> /// <param name="encodedImage"> /// The reference to the encoded image with the reference to the /// encoded bytes. /// </param> /// <param name="bitmapConfig"> /// The <see cref="BitmapPixelFormat"/> used to create the decoded /// SoftwareBitmap. /// </param> /// <returns>The bitmap.</returns> /// <exception cref="OutOfMemoryException"> /// If the Bitmap cannot be allocated. /// </exception> public Task <CloseableReference <SoftwareBitmap> > DecodeFromEncodedImageAsync( EncodedImage encodedImage, BitmapPixelFormat bitmapConfig) { Stream inputStream = encodedImage.GetInputStream(); Preconditions.CheckNotNull(inputStream); return(_executor.Execute(async() => { BitmapDecoder decoder = await BitmapDecoder.CreateAsync( inputStream.AsRandomAccessStream()) .AsTask() .ConfigureAwait(false); SoftwareBitmap bitmap = await decoder .GetSoftwareBitmapAsync(bitmapConfig, BitmapAlphaMode.Premultiplied) .AsTask() .ConfigureAwait(false); return CloseableReference <SoftwareBitmap> .of(bitmap); }) .Unwrap()); }
private Task <bool> ContainsAsync(ICacheKey key) { try { return(_readExecutor.Execute(() => CheckInStagingAreaAndFileCache(key))); } catch (Exception) { // Log failure // TODO: 3697790 Debug.WriteLine($"Failed to schedule disk-cache read for { key.ToString() }"); throw; } }
/// <summary> /// /// </summary> /// <param name="job"></param> /// <returns></returns> public virtual bool ExecuteAsyncJob(IJob job) { if (isMessageQueueMode) { // When running with a message queue based job executor, // the job is not executed here. return(true); } if (isActive) { ThreadStart runnable = CreateRunnableForJob(job); try { executorService.Execute(runnable); } catch (Exception e) { // When a RejectedExecutionException is caught, this means that the queue for holding the jobs // that are to be executed is full and can't store more. // The job is now 'unlocked', meaning that the lock owner/time is set to null, // so other executors can pick the job up (or this async executor, the next time the // acquire query is executed. // This can happen while already in a command context (for example in a transaction listener // after the async executor has been hinted that a new async job is created) // or not (when executed in the acquire thread runnable) ICommandContext commandContext = Context.CommandContext; if (commandContext != null) { commandContext.JobManager.Unacquire(job); } else { processEngineConfiguration.CommandExecutor.Execute(new CommandAnonymousInnerClass(this, job)); } // Job queue full, returning true so (if wanted) the acquiring can be throttled return(false); } } else { temporaryJobQueue.Enqueue(job); } return(true); }
/// <summary> /// Start producing results for given context. /// Provided consumer is notified whenever progress is made /// (new value is ready or error occurs). /// </summary> public void ProduceResults( IConsumer <EncodedImage> consumer, IProducerContext producerContext) { IProducerListener listener = producerContext.Listener; string requestId = producerContext.Id; ImageRequest imageRequest = producerContext.ImageRequest; StatefulProducerRunnable <EncodedImage> cancellableProducerRunnable = new StatefulProducerRunnableImpl <EncodedImage>( consumer, listener, ProducerName, requestId, null, null, null, null, null, null, (result) => { EncodedImage.CloseSafely(result); }, async() => { EncodedImage encodedImage = await GetEncodedImage(imageRequest) .ConfigureAwait(false); if (encodedImage == null) { return(null); } await encodedImage.ParseMetaDataAsync().ConfigureAwait(false); return(encodedImage); }); producerContext.AddCallbacks( new BaseProducerContextCallbacks( () => { cancellableProducerRunnable.Cancel(); }, () => { }, () => { }, () => { })); _executor.Execute(cancellableProducerRunnable.Runnable); }
[Test] public void NewDefaultThreadFactoryHasSpecifiedPriorityBackgroundStatusAndName() { Action r = ThreadManager.GetManagedAction( delegate { Thread current = Thread.CurrentThread; Assert.IsTrue(!current.IsBackground); Assert.IsTrue(current.Priority <= ThreadPriority.Normal); String name = current.Name; Assert.IsTrue(name.EndsWith("thread-1")); }); IExecutorService e = Executors.NewSingleThreadExecutor(Executors.NewDefaultThreadFactory()); e.Execute(r); e.Shutdown(); Thread.Sleep(Delays.Short); JoinPool(e); ThreadManager.JoinAndVerify(); }
public static void Main(string[] args) { Properties options = StringUtils.ArgsToProperties(args, ArgOptionDefs()); if (args.Length < 1 || options.Contains("help")) { log.Info(Usage()); return; } Pattern posPattern = options.Contains("searchPos") ? Pattern.Compile(options.GetProperty("searchPos")) : null; Pattern wordPattern = options.Contains("searchWord") ? Pattern.Compile(options.GetProperty("searchWord")) : null; bool plainPrint = PropertiesUtils.GetBool(options, "plain", false); bool ner = PropertiesUtils.GetBool(options, "ner", false); bool detailedAnnotations = PropertiesUtils.GetBool(options, "detailedAnnotations", false); string[] remainingArgs = options.GetProperty(string.Empty).Split(" "); IList <File> fileList = new List <File>(); foreach (string remainingArg in remainingArgs) { fileList.Add(new File(remainingArg)); } SpanishXMLTreeReaderFactory trf = new SpanishXMLTreeReaderFactory(true, true, ner, detailedAnnotations); IExecutorService pool = Executors.NewFixedThreadPool(Runtime.GetRuntime().AvailableProcessors()); foreach (File file in fileList) { pool.Execute(null); } pool.Shutdown(); try { pool.AwaitTermination(long.MaxValue, TimeUnit.Nanoseconds); } catch (Exception e) { throw new RuntimeInterruptedException(e); } }
private void NotifyDataSubscriber( IDataSubscriber <T> dataSubscriber, IExecutorService executor, bool isFailure, bool isCancellation) { executor.Execute(() => { if (isFailure) { dataSubscriber.OnFailure(this); } else if (isCancellation) { dataSubscriber.OnCancellation(this); } else { dataSubscriber.OnNewResult(this); } }); }
public void SetVideoEnabled(bool enable) { _executor.Execute(() => { _renderVideo = enable; if (_localVideoTrack != null) { _localVideoTrack.IsEnabled = _renderVideo; } if (_remoteVideoTrack != null) { _remoteVideoTrack.IsEnabled = _renderVideo; } }); }
public void Connect(ConnectionParameters connectionParameters) { _connectionParameters = connectionParameters; _executor.Execute(ConnectInternal); }
public virtual void Execute(IRunnable command) { _executorService.Execute(command); }
/// <summary> /// Start producing results for given context. /// Provided consumer is notified whenever progress is made /// (new value is ready or error occurs). /// </summary> public void ProduceResults( IConsumer <EncodedImage> consumer, IProducerContext producerContext) { IProducerListener listener = producerContext.Listener; string requestId = producerContext.Id; ImageRequest imageRequest = producerContext.ImageRequest; StatefulProducerRunnable <EncodedImage> cancellableProducerRunnable = new StatefulProducerRunnableImpl <EncodedImage>( consumer, listener, PRODUCER_NAME, requestId, null, null, null, (result) => { IDictionary <string, string> extraMap = new Dictionary <string, string>() { { CREATED_THUMBNAIL, (result != null).ToString() } }; return(new ReadOnlyDictionary <string, string>(extraMap)); }, null, null, (result) => { EncodedImage.CloseSafely(result); }, async() => { Uri sourceUri = imageRequest.SourceUri; StorageFile file = await StorageFile .GetFileFromApplicationUriAsync(sourceUri) .AsTask() .ConfigureAwait(false); using (var fileStream = await file.OpenReadAsync().AsTask().ConfigureAwait(false)) { byte[] bytes = await BitmapUtil .GetThumbnailAsync(fileStream) .ConfigureAwait(false); if (bytes != null) { IPooledByteBuffer pooledByteBuffer = _pooledByteBufferFactory.NewByteBuffer(bytes); return(await BuildEncodedImage(pooledByteBuffer, fileStream) .ConfigureAwait(false)); } else { return(null); } } }); producerContext.AddCallbacks( new BaseProducerContextCallbacks( () => { cancellableProducerRunnable.Cancel(); }, () => { }, () => { }, () => { })); _executor.Execute(cancellableProducerRunnable.Runnable); }
public override void Execute(IRunnable command) { _executorService.Execute(command); }
public async void Connect(RoomConnectionParameters connectionParameters) { _connectionParameters = connectionParameters; _executor.Execute(ConnectToRoomInternal); }