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(); }
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; }
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; }
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; }
/// <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; }
public Server(int port) { this.port = port; m_ServerSemaphore = new Semaphore(20,20); errorHandler = new ErrorPageHandler(); ext = XMLParser.DeserializeExtensionXML(); }
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; }
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; }
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(); }
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); } }
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; }
internal ServerState() { this.PortNumber = String.Empty; this.Password = String.Empty; this.MainPort = null; this.Clients = new Dictionary<String, TaskInfo>(); this.wChatClipboard = null; this.Transmitting = false; this.WorkEnd = false; this.VideoOn = false; this.SelectingArea = false; this.StreamingSem = null; this.Spawner = null; this.Transfer = null; this.Streamer = null; this.Area = new Rectangle(0,0,0,0); this.hWnd = IntPtr.Zero; this.dUpdateHistory = null; this.dUpdateClipboard = null; this.dSendClipboard = null; this.PreviousBMP = null; this.CurrentBMP = null; this.SelectedWindowOffsetX = 0; this.SelectedWindowOffsetY = 0; }
}; // 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(); }
public Barrier(uint count) { threadCount = count; mutex = new Semaphore(1, 1); sem = new Semaphore(0, (int) count); sem2 = new Semaphore(0, (int)count); }
public void StartUDPListener() { userSemaphore = new Semaphore(1, 1); Thread receivingThread = new Thread(messageReceiver); receivingThread.Start(); SetTimer(); }
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; }
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; }
public void TestSemaphore() { Semaphore s = new Semaphore(2); Task t1 = Task.Factory.StartNew(s.Enter); bool t1Result = t1.Wait(TimeSpan.FromSeconds(1)); // should acquire access Assert.IsTrue(t1Result); Task t2 = Task.Factory.StartNew(s.Enter); bool t2result = t2.Wait(TimeSpan.FromSeconds(2)); // should acquire access Assert.IsTrue(t2result); Task t3 = Task.Factory.StartNew(s.Enter); // Goes on wait indefinitely untill someone releases and signals bool t3Result = t3.Wait(TimeSpan.FromSeconds(3)); // since t3 wont complete in 3 sec, the wait is going to return with false. Assert.IsFalse(t3Result); // only max of 2 tasks allowed into the semaphore. // we acquired 3 locks, so // release 2 semaphore locks for next task t4. Task tr1 = Task.Factory.StartNew(s.Release); Task tr2 = Task.Factory.StartNew(s.Release); // now t4 should acquire access. Task t4 = Task.Factory.StartNew(s.Enter); bool t4Result = t4.Wait(TimeSpan.FromSeconds(4)); Assert.IsTrue(t4Result); }
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; }
public RestrictedTaskDispatcher(int maxParallelism) { workWaiter = new ManualResetEvent(false); workSemaphore = new Semaphore(maxParallelism, maxParallelism); workDispatchThread = new Thread(WorkDispatcher); workDispatchThread.Start(); }
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(); }
/// <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(); } }
private Stopwatch _watch; //for testing #endregion Fields #region Constructors public SocketListener(int maxConnectionCount, int bufferSize) { _maxConnectionCount = maxConnectionCount; _bufferSize = bufferSize; _socketAsyncReceiveEventArgsPool = new SocketAsyncEventArgsPool(maxConnectionCount); _socketAsyncSendEventArgsPool = new SocketAsyncEventArgsPool(maxConnectionCount); _acceptedClientsSemaphore = new Semaphore(maxConnectionCount, maxConnectionCount); sendingQueue = new BlockingCollection<MessageData>(); sendMessageWorker = new Thread(new ThreadStart(SendQueueMessage)); for (int i = 0; i < maxConnectionCount; i++) { SocketAsyncEventArgs socketAsyncEventArgs = new SocketAsyncEventArgs(); socketAsyncEventArgs.Completed += OnIOCompleted; socketAsyncEventArgs.SetBuffer(new Byte[bufferSize], 0, bufferSize); _socketAsyncReceiveEventArgsPool.Push(socketAsyncEventArgs); } for (int i = 0; i < maxConnectionCount; i++) { SocketAsyncEventArgs socketAsyncEventArgs = new SocketAsyncEventArgs(); socketAsyncEventArgs.Completed += OnIOCompleted; socketAsyncEventArgs.SetBuffer(new Byte[bufferSize], 0, bufferSize); _socketAsyncSendEventArgsPool.Push(socketAsyncEventArgs); } waitSendEvent = new AutoResetEvent(false); }
/// <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(); }
public CompanyTcpIPIO(IPAddress ipAddress) { _semaphore = new Semaphore(1, 1); _tcpClient = new TcpClient(); _tcpClient.ReceiveTimeout = 1000; _tcpClient.Connect(ipAddress, 2001); _tcpClient.Client.Receive(new byte[1000]); // Discard unsynchronized data }
public void Ctor_NameUsedByOtherSynchronizationPrimitive_Windows() { string name = Guid.NewGuid().ToString("N"); using (Semaphore s = new Semaphore(1, 1, name)) { Assert.Throws<WaitHandleCannotBeOpenedException>(() => new Mutex(false, name)); } }
public Connection(IConnectionSettings settings) { if (settings == null) throw new ArgumentNullException("settings"); this._ConnectionSettings = settings; this._ResourceLock = new Semaphore(settings.MaximumAsyncConnections, settings.MaximumAsyncConnections); }
protected virtual void OnSemafoorDetected(IUserChangedEvent userEvent, Semaphore semafoor) { EventHandler<KinectSemaphoreGestureEventArgs> handler = SemafoorDetected; if (handler != null) { handler(this, new KinectSemaphoreGestureEventArgs(userEvent, semafoor)); } }
public KeyAuthServer(int maxRequests, int port) { this.m_maxRequests = maxRequests; this.m_port = port; m_semaphore = new Semaphore(0, m_maxRequests); InitHttpListener(); }
public void TestThrowOnMoreInitialUsersThanMaximumUsers() { Assert.Throws<ArgumentOutOfRangeException>( delegate() { Semaphore semaphore = new Semaphore(2, 1); semaphore.Close(); } ); }
public Form1() { InitializeComponent(); /* Registramos los mensajes*/ MSG_ENTRA = RegisterWindowMessage("MSG_ENTRA"); MSG_COGE_TOALLA = RegisterWindowMessage("MSG_COGE_TOALLA"); MSG_DEJA_TOALLA = RegisterWindowMessage("MSG_DEJA_TOALLA"); MSG_DUCHA_IN = RegisterWindowMessage("MSG_DUCHA_IN"); MSG_DUCHA_OUT = RegisterWindowMessage("MSG_DUCHA_OUT"); /* Inicializamos el mutex y el semaforo*/ semaphor = Semaphore.OpenExisting("spa delux"); mutexUsuario = Mutex.OpenExisting("mutex spa"); /* Obtenemos la ventana para lanzar el mensaje*/ IntPtr h = Process.GetProcessesByName("UnSpaDelux")[0].MainWindowHandle; /* Comprueba que no estan limpiando*/ Boolean result; /* Creamos el mutex de limpieza*/ Mutex mutexLimpieza; do { mutexLimpieza = new Mutex(false, "mutexLimpieza", out result); mutexLimpieza.Dispose(); } while (!result); mutexLimpieza = new Mutex(false, "mutexDuchante", out result); /* Mandamos mensaje Entra en el spa un usuario*/ PostMessage(h, MSG_ENTRA, IntPtr.Zero, IntPtr.Zero); /* Espera a que este vacio el proceso para coger una toalla*/ semaphor.WaitOne(); /* Mandamos mensaje Usuario coge toalla*/ PostMessage(h, MSG_COGE_TOALLA, IntPtr.Zero, IntPtr.Zero); /* Entra en la ducha y la bloquea*/ mutexUsuario.WaitOne(); /* Mandamos mensaje Usuario entra ducha*/ PostMessage(h, MSG_DUCHA_IN, IntPtr.Zero, IntPtr.Zero); /* Una vez el usuario entra en la ducha el tiempo que esta dentro*/ /* Momento en el que entramos*/ int actual = DateTime.Now.Millisecond; int quiere = new Random(actual).Next(1000, 4500); do { timeo++; Console.Write("Tro lo lo lololo lolo trolololo"); } while (timeo % 45000 != 0 /*(DateTime.Now.Millisecond - actual) < 1500*/); Console.Clear(); Console.WriteLine("Fin de ducha"); /* Liberamos la ducha*/ mutexUsuario.ReleaseMutex(); /* Mandamos mensaje Usuario sale ducha*/ PostMessage(h, MSG_DUCHA_OUT, IntPtr.Zero, IntPtr.Zero); /* Dejamos la toalla libre*/ semaphor.Release(); /* Mandamos mensaje Usuario deja la toalla*/ PostMessage(h, MSG_DEJA_TOALLA, IntPtr.Zero, IntPtr.Zero); mutexLimpieza.Dispose(); //Console.ReadLine(); Dispose(); }
private void InitSemaphore() { semaphoreFull = Semaphore.OpenExisting("DebuggerFull"); semaphoreEmpty = Semaphore.OpenExisting("DebuggerEmpty"); }
public NormalServer(int numConnections, int receiveBufferSize) : base(numConnections, receiveBufferSize) { m_numConnectedSockets = 0; m_maxNumberAcceptedClients = new Semaphore(numConnections, numConnections); }
public MapManager() { this.gameLoaded = false; _pool = new Semaphore(1, 1); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="downloadFolder">The file to which the report is downloaded. /// </param> public void Run(AdWordsUser user, string downloadFolder) { // Increase the number of HTTP connections we can do in parallel. System.Net.ServicePointManager.DefaultConnectionLimit = 100; try { // Start the rate limiter with an initial value of zero, so that all // threads block immediately. Semaphore rateLimiter = new Semaphore(0, MAX_REPORT_DOWNLOADS_IN_PARALLEL); // Get all the advertiser accounts under this manager account. List <long> allCustomerIds = GetDescendantAdvertiserAccounts(user); // Create a concurrent queue of customers so that all threads can work // on the collection in parallel. ConcurrentQueue <long> customerQueue = new ConcurrentQueue <long>(allCustomerIds); // Create queues to keep track of successful and failed report downloads. ConcurrentQueue <SuccessfulReportDownload> reportsSucceeeded = new ConcurrentQueue <SuccessfulReportDownload>(); ConcurrentQueue <FailedReportDownload> reportsFailed = new ConcurrentQueue <FailedReportDownload>(); // Keep an array of events. This is used by the main thread to wait for // all worker threads to join. ManualResetEvent[] doneEvents = new ManualResetEvent[MAX_NUMBER_OF_THREADS]; // The list of threads to download reports. Thread[] threads = new Thread[MAX_NUMBER_OF_THREADS]; // The data for each thread. ReportDownloadData[] threadData = new ReportDownloadData[MAX_NUMBER_OF_THREADS]; // The query to be run on each account. string query = "SELECT CampaignId, AdGroupId, Impressions, Clicks, Cost from " + "ADGROUP_PERFORMANCE_REPORT where AdGroupStatus IN [ENABLED, PAUSED] " + "DURING LAST_7_DAYS"; // Initialize the threads and their data. for (int i = 0; i < MAX_NUMBER_OF_THREADS; i++) { doneEvents[i] = new ManualResetEvent(false); threadData[i] = new ReportDownloadData() { Config = (AdWordsAppConfig)(user.Config.Clone()), DownloadFolder = downloadFolder, SignalEvent = doneEvents[i], ThreadIndex = i, QuotaLock = rateLimiter, CustomerIdQueue = customerQueue, SuccessfulReports = reportsSucceeeded, FailedReports = reportsFailed }; threads[i] = new Thread(threadData[i].ThreadCallback); } // Start the threads. Since the initial value of rate limiter is zero, // all threads will block immediately. for (int i = 0; i < threads.Length; i++) { threads[i].Start(query); } // Now reset the rate limiter so all threads can start downloading reports. rateLimiter.Release(MAX_REPORT_DOWNLOADS_IN_PARALLEL); // Wait for all threads in pool to complete. WaitHandle.WaitAll(doneEvents); Console.WriteLine("Download completed, results:"); Console.WriteLine("Successful reports:"); while (!reportsSucceeeded.IsEmpty) { SuccessfulReportDownload success = null; if (reportsSucceeeded.TryDequeue(out success)) { Console.WriteLine("Client ID: {0}, Path: {1}", success.CustomerId, success.Path); } } Console.WriteLine("Failed reports:"); while (!reportsFailed.IsEmpty) { FailedReportDownload failure = null; if (reportsFailed.TryDequeue(out failure)) { Console.WriteLine("Client ID: {0}, Cause: {1}", failure.CustomerId, failure.Exception.Message); } } Console.WriteLine("All reports are downloaded."); } catch (Exception e) { throw new System.ApplicationException("Failed to download reports.", e); } }
public MultiCellBuffer() { this.currentBufferSize = 0; this.semaphore = new Semaphore(MAXIMUM_BUFFER_SIZE, MAXIMUM_BUFFER_SIZE); this.buffer = new string[MAXIMUM_BUFFER_SIZE]; }
/// <summary> /// TaskScheduler扩展 /// 每个实例都是独立线程池 /// </summary> /// <param name="coreThreadCount">核心线程数(大于或等于0,不宜过大)(如果是一次性使用,则设置为0比较合适)</param> /// <param name="maxThreadCount">最大线程数</param> public TaskSchedulerEx(int coreThreadCount = 10, int maxThreadCount = 20) { _sem = new Semaphore(0, _semMaxCount); _maxThreadCount = maxThreadCount; CreateCoreThreads(coreThreadCount); }
/// <summary> /// partition master, partition data[left,right] and return the position of the pivot /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> private int paraPartitionMaster(int left, int right) { if (right <= left) { return(left); } else if (right - left < _divideSize) { return(_randomizedPartition(left, right)); } int changeIndex = _r.Next(left, right); Utilities.Swap(ref _data[changeIndex], ref _data[right]); // for randomization int pivotValue = _data[right]; int partitionSize = (right - left + 1) / _nprocs; // Step one, threads count the # of elements bigger or smaller // than pivot value, divided uniformally Semaphore server = new Semaphore(0, _nprocs); int[] smaller = new int[_nprocs]; int[] bigger = new int[_nprocs]; Semaphore[] client = new Semaphore[_nprocs]; for (int i = 0; i < _nprocs; i++) { client[i] = new Semaphore(0, 1); } Thread[] partitionThreads = new Thread[_nprocs]; for (int i = 0; i < _nprocs; i++) { int leftPointer = left + i * partitionSize; int rightPointer = left + (i + 1) * partitionSize - 1; if (i == _nprocs - 1) { rightPointer = right; } object[] paras = new object[8] { i, leftPointer, rightPointer, pivotValue, server, client[i], smaller, bigger }; partitionThreads[i] = new Thread( new ParameterizedThreadStart(tParaPartitionClient)); partitionThreads[i].Start(paras); } for (int i = 0; i < _nprocs; i++) { server.WaitOne(); } for (int i = 0; i < _nprocs; i++) { client[i].Release(); } // above for barrier for counting for (int i = 0; i < _nprocs; i++) { server.WaitOne(); } for (int i = 0; i < _nprocs; i++) { client[i].Release(); } // above for barrier for sending data to share space for (int i = 0; i < _nprocs; i++) { server.WaitOne(); } // above for waiting for overwriting int ret = left - 1; for (int i = 0; i < _nprocs; i++) { ret += smaller[i]; } return(ret); }
public Program(string[] args) { int threads = 1; String date = args[0]; int tileMatrix = Int32.Parse(args[1]); try { threads = Int32.Parse(args[2]); } catch { } semaphore = new Semaphore(threads, threads); Console.WriteLine("Threads: " + threads); //Thread.Sleep(2000); Console.WriteLine("Downloading Date: " + date + ", TileMatrix: " + tileMatrix); double tileSize = 288 / Math.Pow(2, tileMatrix); int maxCol = (int)(360 / tileSize); int maxRow = (int)(180 / tileSize); String url = "https://gibs-{a-c}.earthdata.nasa.gov/wmts/epsg4326/best/wmts.cgi?TIME=" + date + "T00:00:00Z&layer=VIIRS_SNPP_CorrectedReflectance_TrueColor&style=default&tilematrixset=250m&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/jpeg&TileMatrix=" + tileMatrix + "&TileCol={TileCol}&TileRow={TileRow}"; int totalFiles = maxRow * maxCol; DirectoryInfo outDi = new DirectoryInfo("out"); if (!outDi.Exists) { outDi.Create(); } DirectoryInfo dateDi = new DirectoryInfo(outDi.FullName + "\\" + date); if (!dateDi.Exists) { dateDi.Create(); } DirectoryInfo tileDi = new DirectoryInfo(dateDi.FullName + "\\TileMatrix" + tileMatrix); if (!tileDi.Exists) { tileDi.Create(); } char[] serverVariation = new char[] { 'a', 'b', 'c' }; Random r = new Random(); for (int row = 0; row < maxRow; row++) { for (int col = 0; col < maxCol; col++) { FileInfo fileInfo = new FileInfo(tileDi.FullName + "\\" + row + "_" + col + ".jpg"); int currentFile = row * maxCol + col; double progress = ((double)currentFile) / totalFiles; String downloadUrl = url.Replace("{TileCol}", "" + col) .Replace("{TileRow}", "" + row). Replace("{a-c}", "" + serverVariation[r.Next() % 3]); //Console.WriteLine(String.Format("{0:P2}.", progress)+"\t"+downloadUrl); Console.Write(String.Format("{0:P2}.", progress) + "\t" + date + "\t" + tileMatrix + "\t" + row + "\t" + col + "\t"); if (fileInfo.Exists && fileInfo.Length > 0) { Console.WriteLine("File exists, " + fileInfo.Length + " bytes, skipping..."); continue; } else { Console.Write("Download...\t"); DownloadTask downloadTask = new DownloadTask() { FileName = fileInfo.FullName, Url = downloadUrl }; semaphore.WaitOne(); Thread t = new Thread(new ParameterizedThreadStart(Worker)); t.Start(downloadTask); } } } for (int i = 0; i < threads; i++) { semaphore.WaitOne(); } }
/// <summary> /// Creates a new instance of the <see cref="InterprocessReaderWriterLock"/> associated with the specified /// <paramref name="name"/> that identifies a source object needing concurrency locking. /// </summary> /// <param name="name">Identifying name of source object needing concurrency locking (e.g., a path and file name).</param> /// <param name="maximumConcurrentLocks">Maximum concurrent reader locks to allow.</param> /// <remarks> /// If more reader locks are requested than the <paramref name="maximumConcurrentLocks"/>, excess reader locks will simply /// wait until a lock is available (i.e., one of the existing reads completes). /// </remarks> public InterprocessReaderWriterLock(string name, int maximumConcurrentLocks) { m_maximumConcurrentLocks = maximumConcurrentLocks; m_semaphoreLock = InterprocessLock.GetNamedMutex(name); m_concurrencyLock = InterprocessLock.GetNamedSemaphore(name, m_maximumConcurrentLocks); }
internal NamedSemaphoreReleaser(Semaphore semaphore) { _semaphore = semaphore; _handle = GCHandle.Alloc(_semaphore); }
//protected void /*bool*/ ExpRDGExcelValuesRequest() //{ //} /// <summary> /// Инициализация синхронизации состояния /// </summary> protected override void InitializeSyncState() { m_semaIndxTECComponents = new Semaphore(1, 1); base.InitializeSyncState(); }
public BinarySemaphore(int start, int end) { _count = 0; _sem = new Semaphore(start, end); }
public Elevator() { currentFloor = FloorLevel.G; // initial floor level semaphore = new Semaphore(1, 1); // allowing only one agent inside }
public ExecutorQueue() { queue = new Queue <ExecutorMessage>(); semaphore = new Semaphore(0, Settings.Default.QueuesMaxThreads); }
public ComputerInTaskHandler(ExecutedTaskData _executedTaskData, List <ClientHandler> _clients, int _index, List <string> _ipAddresses, Semaphore _semaphoreFotSaveFile, ListView _listViewAll, ListView _listViewSelected) { step = "WAITING FO ACK"; semaphoreForTask.WaitOne(); this.executedTaskData = _executedTaskData; this.clients = _clients; this.index = _index; this.ipAddresses = _ipAddresses; this.taskData = executedTaskData.taskData; this.semaphoreForSaveFile = _semaphoreFotSaveFile; this.listViewAll = _listViewAll; this.listViewSelected = _listViewSelected; receivePacket = new Packet(DataIdentifier.CLOSE); computer = executedTaskData.taskData.TargetComputers[index]; }
/// <inheritdoc/> public void InterceptionPointStart(InterceptionPoint interceptionPoint, object instance = null, object[] parameters = null) { /* * if (!this.isTrapActive && bugFound) * throw new Exception("ThreadSafety bugs detected by Torch"); */ bool newTrapsAllowed = true; bool newBugFound = false; if (this.configuration == null || this.configuration.ThreadSafetyGroups == null) { return; } ThreadSafetyInterceptionPoint threadSafetyInterceptionPoint = ControllerHelper.GetThreadSafetyInterceptionPoint(this.configuration.ThreadSafetyGroups, interceptionPoint); if (threadSafetyInterceptionPoint == null) { return; } if (!threadSafetyInterceptionPoint.ThreadSafetyGroup.IsStatic && instance == null) { return; } string groupName = threadSafetyInterceptionPoint.ThreadSafetyGroup.Name; Dictionary <Guid, Trap> trapObjects = null; lock (this.trapPoints) { if (!this.trapPoints.ContainsKey(groupName)) { this.trapPoints.Add(groupName, new Dictionary <Guid, Trap>()); if (threadSafetyInterceptionPoint.IsWriteAPI) { this.writeTrapPoints.Add(groupName); } } trapObjects = this.trapPoints[groupName]; } Semaphore semaphore = null; int sleepDuration = 0; Guid keyInstance = ObjectId.GetRefId(null); lock (trapObjects) { if (!threadSafetyInterceptionPoint.ThreadSafetyGroup.IsStatic) { keyInstance = ObjectId.GetRefId(instance); } // Check if a trap on this object is live Trap trap = null; trapObjects.TryGetValue(keyInstance, out trap); // A bug is found if there is a trap on this object and // either this access or trapped access is a write if (trap != null && (threadSafetyInterceptionPoint.IsWriteAPI || trap.ThreadSafetyInterceptionPoint.IsWriteAPI)) { // Get stack track when a bug is found. interceptionPoint.StackTrace = Environment.StackTrace; ControllerHelper.WriteBug(trap, interceptionPoint); newBugFound = true; try { trap.Semaphore.Release(); } catch (SemaphoreFullException) { } } else if (newTrapsAllowed) { // prepare to set up a trap if (!this.isTrapActive) { if (threadSafetyInterceptionPoint.IsWriteAPI && this.random.NextDouble() <= this.DelayProbability) { // Get stack trace only if setting up a trap. interceptionPoint.StackTrace = Environment.StackTrace; semaphore = new Semaphore(0, 1); sleepDuration = this.random.Next(this.MaxDelayPerInterceptionPoint); trap = new Trap { ObjectId = keyInstance, Semaphore = semaphore, InterceptionPoint = interceptionPoint, ThreadSafetyInterceptionPoint = threadSafetyInterceptionPoint, Delay = sleepDuration, }; ControllerHelper.WriteTrap(trap); trapObjects.Add(keyInstance, trap); this.isTrapActive = true; } } } } if (semaphore != null) { semaphore.WaitOne(sleepDuration); lock (trapObjects) { trapObjects.Remove(keyInstance); } this.isTrapActive = false; } if (this.configuration.ThrowExceptionOnRace && newBugFound) { throw new Exception("ThreadSafety bugs detected by Torch"); } return; }
//Конструктор класса public Decomress(object _forLock, Queue <Thread> _fifoThreads, Semaphore _semaforForStart, Semaphore _semaforForREAD, FileStream _originalFileStream, int _compressedBlockLength, long _startPosition, FileStream _decompressedFileStream, byte[] _buffer, int _countProcessor) //Конструктор получает имя функции и номер до кторого ведется счет { forLock = _forLock; semaforForStart = _semaforForStart; fifoThreads = _fifoThreads; originalFileStream = _originalFileStream; startPosition = _startPosition; compressedBlockLength = _compressedBlockLength; decompressedFileStream = _decompressedFileStream; canWriting = false; buffer = _buffer; semaforForREAD = _semaforForREAD; countProcessor = _countProcessor; }
/// <summary> /// Required Files Agent /// </summary> public RequiredFilesAgent() { _fileDownloadLimit = new Semaphore(ApplicationSettings.Default.MaxConcurrentDownloads, ApplicationSettings.Default.MaxConcurrentDownloads); _requiredFiles = new RequiredFiles(); }
internal EasyServerAccessController(int maxConnection) { _semaphoreAcceptedClients = new Semaphore(maxConnection, maxConnection); }
public static void CancelMarketPendingListings(UiSteamManager steamManager, WorkingProcessDataContext wp) { MyListingsSalesItem[] myListings; try { myListings = steamManager.MarketClient.MyListings(steamManager.Currency.ToString())?.ConfirmationSales ?.ToArray(); } catch (Exception e) { wp.AppendLog($"Error on fetching market listings - {e.Message}"); return; } if (myListings == null || myListings.Length <= 0) { wp.AppendLog("No market listing found. Nothing to cancel"); return; } wp.AppendLog( $"Seems there are {myListings.Length} market listings that do not have two factor confirmation request. Trying to cancel them"); var semaphore = new Semaphore( SettingsProvider.GetInstance().RelistThreadsCount, SettingsProvider.GetInstance().RelistThreadsCount); var index = 1; foreach (var listing in myListings) { if (wp.CancellationToken.IsCancellationRequested) { return; } if (listing == null) { continue; } try { semaphore.WaitOne(); var realListing = listing; var realIndex = index++; Task.Run( () => { try { var tryCount = 0; while (true) { if (wp.CancellationToken.IsCancellationRequested) { wp.AppendLog( $"Cancel market {realListing.Name} pending listings process was force stopped"); break; } wp.AppendLog($"[{realIndex}/{myListings.Length}] Removing {realListing.Name}"); var result = steamManager.MarketClient.CancelSellOrder(realListing.SaleId); if (result != ECancelSellOrderStatus.Canceled) { wp.AppendLog($"ERROR on removing {realListing.Name}"); if (tryCount++ > 10) { break; } Thread.Sleep(1000); } else { break; } } } catch (Exception e) { wp.AppendLog($"ERROR on removing {realListing.Name} - {e.Message}"); Logger.Log.Error($"ERROR on removing {realListing.Name} - {e.Message}", e); } finally { semaphore.Release(); } }); } catch (Exception e) { wp.AppendLog($"ERROR on removing {listing.Name} - {e.Message}"); Logger.Log.Error($"ERROR on removing {listing.Name} - {e.Message}", e); } } }
private EquihashSolver(int maxConcurrency) { // we need to limit concurrency here due to the enormous memory // requirements of the equihash algorithm (up 1GB per thread) sem = new Semaphore(maxConcurrency, maxConcurrency); }
public void BasicListenerStrongTest() { int step = 0; Semaphore s = new Semaphore(0, 1); Action <Event.CounterEvent> a2 = (Event.CounterEvent e) => { switch (step) { case 0: Assert.AreEqual(5, e.OldValue); Assert.AreEqual(15, e.NewValue); Assert.AreEqual(Event.CounterState.VALID, e.NewState); Assert.AreEqual(Event.CounterState.VALID, e.OldState); s.Release(); break; case 1: Assert.AreEqual(15, e.OldValue); Assert.AreEqual(0, e.NewValue); Assert.AreEqual(Event.CounterState.LOWER_BOUND_REACHED, e.NewState); Assert.AreEqual(Event.CounterState.VALID, e.OldState); s.Release(); break; case 2: Assert.AreEqual(0, e.OldValue); Assert.AreEqual(20, e.NewValue); Assert.AreEqual(Event.CounterState.UPPER_BOUND_REACHED, e.NewState); Assert.AreEqual(Event.CounterState.LOWER_BOUND_REACHED, e.OldState); s.Release(); break; default: Assert.Fail(); break; } }; string counterName = "strongTestBasicListener"; Event.CounterListener cl = new Event.CounterListener(counterName, a2); var rcm = remoteManager.GetCounterManager(); var cc = new CounterConfiguration(5, 0, 20, 8, CounterType.BOUNDED_STRONG, Storage.VOLATILE); rcm.DefineCounter(counterName, cc); var counter = rcm.GetStrongCounter(counterName); object o = counter.AddListener(cl); counter.AddAndGet(10); Assert.True(s.WaitOne(15000)); step = 1; try { counter.AddAndGet(-20); } catch (CounterLowerBoundException) { } Assert.True(s.WaitOne(15000)); step = 2; try { counter.AddAndGet(30); } catch (CounterUpperBoundException) { } Assert.True(s.WaitOne(15000)); counter.RemoveListener(o); }
public SemaphoreLock(Semaphore semaphore) { this.semaphore = semaphore; semaphore.WaitOne(); }
private void TearDown() { device.WaitIdle(); this.renderFinishedSemaphore.Dispose(); this.renderFinishedSemaphore = null; this.imageAvailableSemaphore.Dispose(); this.imageAvailableSemaphore = null; this.descriptorPool.Dispose(); this.descriptorPool = null; this.descriptorSet = null; this.device.FreeMemory(this.uniformBufferMemory); this.uniformBufferMemory = null; this.uniformBuffer.Dispose(); this.uniformBuffer = null; this.device.FreeMemory(this.uniformStagingBufferMemory); this.uniformStagingBufferMemory = null; this.uniformStagingBuffer.Dispose(); this.uniformStagingBuffer = null; this.device.FreeMemory(this.indexBufferMemory); this.indexBufferMemory = null; this.indexBuffer.Dispose(); this.indexBuffer = null; this.device.FreeMemory(this.vertexBufferMemory); this.vertexBufferMemory = null; this.vertexBuffer.Dispose(); this.vertexBuffer = null; this.commandPool.Dispose(); this.commandPool = null; this.commandBuffers = null; foreach (var frameBuffer in this.frameBuffers) { frameBuffer.Dispose(); } this.frameBuffers = null; this.fragShader.Dispose(); this.fragShader = null; this.vertShader.Dispose(); this.vertShader = null; this.pipeline.Dispose(); this.pipeline = null; this.pipelineLayout.Dispose(); this.pipelineLayout = null; foreach (var imageView in this.swapChainImageViews) { imageView.Dispose(); } this.swapChainImageViews = null; this.descriptorSetLayout.Dispose(); this.descriptorSetLayout = null; this.renderPass.Dispose(); this.renderPass = null; this.swapChain.Dispose(); this.swapChain = null; this.device.Dispose(); this.device = null; this.surface.Dispose(); this.surface = null; this.instance.Dispose(); this.instance = null; }
protected override void DoStart() { if (m_Prefixes.Count == 0) { throw new WaveException(StringConsts.SERVER_NO_PREFIXES_ERROR.Args(Name)); } if (!s_Servers.Register(this)) { throw new WaveException(StringConsts.SERVER_COULD_NOT_GET_REGISTERED_ERROR.Args(Name)); } try { if (m_Gate != null) { if (m_Gate is Service) { ((Service)m_Gate).Start(); } } if (m_Dispatcher == null) { m_Dispatcher = new WorkDispatcher(this); } m_Dispatcher.Start(); m_AcceptSemaphore = new Semaphore(m_ParallelAccepts, m_ParallelAccepts); m_WorkSemaphore = new Semaphore(m_ParallelWorks, m_ParallelWorks); m_AcceptThread = new Thread(acceptThreadSpin); m_AcceptThread.Name = "{0}-AcceptThread".Args(Name); m_InstrumentationThread = new Thread(instrumentationThreadSpin); m_InstrumentationThread.Name = "{0}-InstrumentationThread".Args(Name); m_InstrumentationThreadWaiter = new AutoResetEvent(false); m_Listener = new HttpListener(); foreach (var prefix in m_Prefixes) { m_Listener.Prefixes.Add(prefix); } BeforeListenerStart(m_Listener); m_Listener.Start(); AfterListenerStart(m_Listener); m_Listener.IgnoreWriteExceptions = m_IgnoreClientWriteErrors; if (m_KernelHttpQueueLimit != DEFAULT_KERNEL_HTTP_QUEUE_LIMIT) { PlatformUtils.SetRequestQueueLimit(m_Listener, m_KernelHttpQueueLimit); } } catch { closeListener(); if (m_AcceptSemaphore != null) { m_AcceptSemaphore.Dispose(); m_AcceptSemaphore = null; } if (m_WorkSemaphore != null) { m_WorkSemaphore.Dispose(); m_WorkSemaphore = null; } if (m_AcceptThread != null) { m_AcceptThread = null; } if (m_Dispatcher != null) { m_Dispatcher.WaitForCompleteStop(); } if (m_Gate != null && m_Gate is Service) { ((Service)m_Gate).WaitForCompleteStop(); } s_Servers.Unregister(this); throw; } m_InstrumentationThread.Start(); m_AcceptThread.Start(); }
private void CreateSemaphores() { this.imageAvailableSemaphore = device.CreateSemaphore(new SemaphoreCreateInfo()); this.renderFinishedSemaphore = device.CreateSemaphore(new SemaphoreCreateInfo()); }
private void StartListen() { m_ListenSocket = new Socket(this.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { m_ListenSocket.Bind(this.EndPoint); m_ListenSocket.Listen(this.AppServer.Config.ListenBacklog); m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true); } catch (Exception e) { AppServer.Logger.LogError(e); OnStartupFinished(); return; } m_MaxConnectionSemaphore = new Semaphore(this.AppServer.Config.MaxConnectionNumber, this.AppServer.Config.MaxConnectionNumber); SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs(); acceptEventArg.Completed += new EventHandler <SocketAsyncEventArgs>(acceptEventArg_Completed); IsRunning = true; OnStartupFinished(); while (!IsStopped) { m_MaxConnectionSemaphore.WaitOne(); if (IsStopped) { break; } acceptEventArg.AcceptSocket = null; bool willRaiseEvent = true; try { willRaiseEvent = m_ListenSocket.AcceptAsync(acceptEventArg); } catch (ObjectDisposedException)//listener has been stopped { break; } catch (NullReferenceException) { break; } catch (Exception e) { AppServer.Logger.LogError("Failed to accept new tcp client in async server!", e); break; } if (!willRaiseEvent) { AceptNewClient(acceptEventArg); } m_TcpClientConnected.WaitOne(); } IsRunning = false; }
public Elevator(int agents = 1) { this.floor = new Floor(); semaphore = new Semaphore(agents, agents); }
private RemoteService TryStartProcess(CultureInfo culture, CancellationToken cancellationToken) { Process newProcess = null; int newProcessId = -1; Semaphore semaphore = null; try { int currentProcessId = Process.GetCurrentProcess().Id; bool semaphoreCreated; string semaphoreName; while (true) { semaphoreName = "InteractiveHostSemaphore-" + Guid.NewGuid(); semaphore = new Semaphore(0, 1, semaphoreName, out semaphoreCreated); if (semaphoreCreated) { break; } semaphore.Close(); cancellationToken.ThrowIfCancellationRequested(); } var remoteServerPort = "InteractiveHostChannel-" + Guid.NewGuid(); var processInfo = new ProcessStartInfo(_hostPath); processInfo.Arguments = remoteServerPort + " " + semaphoreName + " " + currentProcessId; processInfo.WorkingDirectory = _initialWorkingDirectory; processInfo.CreateNoWindow = true; processInfo.UseShellExecute = false; processInfo.RedirectStandardOutput = true; processInfo.RedirectStandardError = true; processInfo.StandardErrorEncoding = Encoding.UTF8; processInfo.StandardOutputEncoding = Encoding.UTF8; newProcess = new Process(); newProcess.StartInfo = processInfo; // enables Process.Exited event to be raised: newProcess.EnableRaisingEvents = true; newProcess.Start(); InteractiveHostProcessCreated?.Invoke(newProcess); cancellationToken.ThrowIfCancellationRequested(); try { newProcessId = newProcess.Id; } catch { newProcessId = 0; } // sync: while (!semaphore.WaitOne(_millisecondsTimeout)) { if (!CheckAlive(newProcess)) { return(null); } _output.WriteLine(FeaturesResources.Attempt_to_connect_to_process_Sharp_0_failed_retrying, newProcessId); cancellationToken.ThrowIfCancellationRequested(); } // instantiate remote service: Service newService; try { newService = (Service)Activator.GetObject( typeof(Service), "ipc://" + remoteServerPort + "/" + Service.ServiceName); cancellationToken.ThrowIfCancellationRequested(); newService.Initialize(_replServiceProviderType, culture.Name); } catch (RemotingException) when(!CheckAlive(newProcess)) { return(null); } return(new RemoteService(this, newProcess, newProcessId, newService)); } catch (OperationCanceledException) { if (newProcess != null) { RemoteService.InitiateTermination(newProcess, newProcessId); } return(null); } finally { if (semaphore != null) { semaphore.Close(); } } }