public void AddCount_Invalid () { var ev = new CountdownEvent (1); try { ev.AddCount (0); Assert.Fail ("#1"); } catch (ArgumentOutOfRangeException) { } try { ev.AddCount (-1); Assert.Fail ("#2"); } catch (ArgumentOutOfRangeException) { } }
static void Main(string[] args) { var customers = Enumerable.Range(1, 20); using (var countdown = new CountdownEvent(1)) { foreach (var customer in customers) { int currentCustomer = customer; countdown.AddCount(); ThreadPool.QueueUserWorkItem(delegate { BuySomeStuff(currentCustomer); countdown.Signal(); }); } countdown.Signal(); countdown.Wait(); } Console.WriteLine("All Customers finished shopping..."); Console.ReadKey(); }
protected override void ExecuteLevel(IList<Computation> computationsOfLevel) { using (var countEvent = new CountdownEvent(1)) { foreach (var item in computationsOfLevel) { var cc = item.Context as ParallelComputationContext; if (cc != null) { countEvent.AddCount(); cc.RunTransform(() => { item.Transform(); countEvent.Signal(); }); } else { countEvent.Signal(); countEvent.Wait(); item.Transform(); countEvent.Reset(); } OnComputationCompleted(new ComputationEventArgs(item)); } countEvent.Signal(); countEvent.Wait(); } }
public async Task MessageQueueThread_HandlesException() { var exception = new Exception(); var countdown = new CountdownEvent(1); var handler = new Action<Exception>(ex => { Assert.AreSame(exception, ex); countdown.Signal(); }); var uiThread = await CallOnDispatcherAsync(() => MessageQueueThread.Create(MessageQueueThreadSpec.DispatcherThreadSpec, handler)); var backgroundThread = MessageQueueThread.Create(MessageQueueThreadSpec.Create("background", MessageQueueThreadKind.BackgroundSingleThread), handler); var taskPoolThread = MessageQueueThread.Create(MessageQueueThreadSpec.Create("any", MessageQueueThreadKind.BackgroundAnyThread), handler); var queueThreads = new[] { uiThread, backgroundThread, taskPoolThread }; countdown.AddCount(queueThreads.Length - 1); foreach (var queueThread in queueThreads) { queueThread.RunOnQueue(() => { throw exception; }); } Assert.IsTrue(countdown.Wait(5000)); }
public OperationContext(CountdownEvent countdownEvent, ConcurrentOperationManager manager) { _countdownEvent = countdownEvent; _countdownEvent.AddCount(); manager.OnOperationContextCreated(EventArgs.Empty); if(manager._isDisposed) { Dispose(); throw new ObjectDisposedException(manager._owningType); } }
static void Main(string[] args) { //// system io test //// - start a process , redirect output to a memory stream and then run the cmd and send that output to standard out //ProcessStartInfo cmd = new ProcessStartInfo("cmd.exe"); //cmd.RedirectStandardInput = true; //cmd.RedirectStandardOutput = true; //cmd.UseShellExecute = false; //cmd.CreateNoWindow = false; //cmd.WindowStyle = ProcessWindowStyle.Normal; //Process console = Process.Start(cmd); //commandOutputStream = console.StandardOutput; //console.StandardInput.WriteLine(command); //console.StandardInput.WriteLine("EXIT"); //console.WaitForExit(); // uncomment the test to run - OK - I may only end up running one type ;) //// Test - simple run a command + simple queuing //var myCommands = new command(); //System.Console.Out.WriteLine("START"); //System.Console.Out.WriteLine("queue 1"); //System.Threading.ThreadPool.QueueUserWorkItem (new System.Threading.WaitCallback(myCommands.thread1Command)); //System.Console.Out.WriteLine("queue 2"); // System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(myCommands.thread2Command)); //System.Console.Out.WriteLine("END"); // test - multi-queue - used to learn how to wait for the end of tasks & to test general performance // use the countdownevent pattern var myCommands = new command(); //var state = new object(); System.Console.Out.WriteLine("START"); var cde = new System.Threading.CountdownEvent(1); for (var i = 1; i <= 100; i++) { System.Console.Out.WriteLine("queue " + i); System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(myCommands.bogusTask), cde); // increment the counter cde.AddCount(1); } // decrement the counter - we started with one ! // - prevents the race condition where tasks finish before queueing is done ! cde.Signal(); // wait for all tasks to be complete - the final (0) countdown event cde.Wait(); System.Console.Out.WriteLine("END"); }
public static void ScanIPs() { //string hostName = Dns.GetHostName(); // Retrive the Name of HOST //Console.WriteLine(hostName); // Get the IP //string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString(); string myIP = "192.168.1.1"; var bytes = IPAddress.Parse(myIP).GetAddressBytes(); // set the value here bytes[3] = 0; IPAddress ipAddress = new IPAddress(bytes); var IPaddress1 = IPAddress.Parse(myIP).GetAddressBytes()[0].ToString() + "." + IPAddress.Parse(myIP).GetAddressBytes()[1].ToString() + "." + IPAddress.Parse(myIP).GetAddressBytes()[2].ToString() + "."; Console.WriteLine("My IP Address is :" + myIP); Console.WriteLine("Network :" + IPaddress1); //Console.ReadLine(); countdown = new CountdownEvent(1); Stopwatch sw = new Stopwatch(); sw.Start(); //string ipBase = "10.0.0."; for (int i = 1; i < 255; i++) { string ip = IPaddress1 + i.ToString(); Ping p = new Ping(); p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted); countdown.AddCount(); p.SendAsync(ip, 100, ip); } countdown.Signal(); countdown.Wait(); sw.Stop(); TimeSpan span = new TimeSpan(sw.ElapsedTicks); //Console.WriteLine("Took {0} milliseconds. {1} hosts active.", sw.ElapsedMilliseconds, upCount); //Console.WriteLine("\nPress any key to continue..."); //Console.ReadKey(); }
private static void IndexOnPagesInDB_IAMLAZY() { foreach (var page in database.GetAllPages()) { ToBeIndexedQueue.Enqueue(new Tuple<PrettyURL, string, DateTime>(new PrettyURL(page.url), page.html, DateTime.Now)); } CountdownEvent CTE = new CountdownEvent(1); var indexer = new MainIndexer(stopWords, charsToRemove, ToBeIndexedQueue, CTE); Thread indexerThread = new Thread(() => indexer.CreateInverseIndexWriteToDB(true)); CTE.AddCount(); indexerThread.Start(); CTE.Signal(); CTE.Wait(); }
public void AddCount_HasBeenSet() { var ev = new CountdownEvent(0); try { ev.AddCount(1); Assert.Fail("#1"); } catch (InvalidOperationException) { } ev = new CountdownEvent(1); Assert.IsTrue(ev.Signal(), "#2"); try { ev.AddCount(1); Assert.Fail("#3"); } catch (InvalidOperationException) { } }
// perform union on currently selected layer private void unionButton_Click(object sender, EventArgs e) { toolBuilder.addHeader("Union"); // textbox for new layername TextBox textbox = toolBuilder.addTextboxWithCaption("New layername:"); Label errorLabel = toolBuilder.addErrorLabel(); Button button = toolBuilder.addButton("Union", (Layer l) => { // user has not set new layername if (textbox.Text.Length == 0) { toolBuilder.setError("Provide name"); return; } // create temporary layer Layer copyLayer = new Layer(l.Name); copyLayer.Boundingbox = new Envelope(l.Boundingbox); copyLayer.createQuadTree(); // copy all features to temp layer foreach (Feature f in l.Features.Values) copyLayer.addFeature(new Feature((IGeometry)f.Geometry.Clone(), f.ID)); // create new layer with same boundingbox Layer newLayer = new Layer(textbox.Text); newLayer.Boundingbox = new Envelope(l.Boundingbox); newLayer.createQuadTree(); // init progress bar int numFeatures = copyLayer.Features.Values.Count; progressLabel.Text = "Performing union"; progressBar.Minimum = 0; progressBar.Maximum = numFeatures; BackgroundWorker bw = new BackgroundWorker(); bw.WorkerReportsProgress = true; // perform merge in another thread bw.DoWork += (object wsender, DoWorkEventArgs we) => { // threadsafe list of merged features ConcurrentBag<Feature> newFeatures = new ConcurrentBag<Feature>(); var finished = new CountdownEvent(1); Object _lock = new object(); // create thread function var merge = new WaitCallback((state) => { Random rnd = new Random(); while (true) { Feature f; lock (_lock) { // break if no more features if (copyLayer.Features.Count == 0) break; // get random index int index = rnd.Next(copyLayer.Features.Count); // get corresponding random feature f = copyLayer.Features[copyLayer.Features.Keys.ToList()[index]]; // remove feature from layer copyLayer.delFeature(f); } f.ID = -1; while (true) { List<Feature> intersects; // aquire lock to avoid race conditions lock (_lock) { // get all features intersecting feature intersects = copyLayer.getWithin(f.Geometry); // remove features from layer foreach (Feature intersect in intersects) copyLayer.delFeature(intersect); } // if no intersects, no merging is necessary if (intersects.Count == 0) break; // merge all features foreach (Feature intersect in intersects) { f = new Feature(f.Geometry.Union(intersect.Geometry)); bw.ReportProgress(1); } } // add feature to list of new features newFeatures.Add(f); } finished.Signal(); }); // spawn eight threads, this is not always optimal but a good approximation for (int i = 0; i < 8; i++) { finished.AddCount(); ThreadPool.QueueUserWorkItem(merge); } finished.Signal(); finished.Wait(); bw.ReportProgress(-newFeatures.Count); // add all merged features back to temp layer foreach (Feature f in newFeatures) copyLayer.addFeature(f); newFeatures = new ConcurrentBag<Feature>(); finished = new CountdownEvent(1); // perform a final single threaded merge merge(false); // add all final merged features to new layer foreach (Feature f in newFeatures) newLayer.addFeature(f); }; bw.RunWorkerCompleted += (object wsender, RunWorkerCompletedEventArgs we) => { // reset progress bar progressBar.Value = 0; progressLabel.Text = ""; // insert new layer and redraw map Layers.Insert(0, newLayer); redraw(); }; bw.ProgressChanged += (object wsender, ProgressChangedEventArgs we) => { // update progress bar if (we.ProgressPercentage < 0) { progressBar.Value = 0; progressBar.Maximum = -we.ProgressPercentage; progressLabel.Text = "Union - Second pass"; } else progressBar.Value += we.ProgressPercentage; }; bw.RunWorkerAsync(); }); // reset default new layer name when selected layer is changed toolBuilder.resetAction = (Layer l) => { textbox.Text = (l == null) ? "" : l.Name + "_union"; }; toolBuilder.reset(); }
public List<NetworkEntry> GetNetworkInformation(string ipRange, bool resolveNames=true, int timeout=75, bool onlyUpDevices=true) { //Setup List<NetworkEntry> ret=new List<NetworkEntry>(); CountdownEvent countdown=new CountdownEvent(1); string[] parts=ipRange.Split(new char[] { '.', '/' }, StringSplitOptions.RemoveEmptyEntries); int netmaskBits=32-Convert.ToInt32(parts[4]); //24 is var if(netmaskBits>30) throw new NotSupportedException("Only netmasks lower or equal 30 are supported"); //Convert ip Adress into uint uint ipBase=0; ipBase+=Convert.ToUInt32(parts[0])<<24; ipBase+=Convert.ToUInt32(parts[1])<<16; ipBase+=Convert.ToUInt32(parts[2])<<8; ipBase+=Convert.ToUInt32(parts[3]); //<<0 uint netmask=~((1u<<netmaskBits)-1u); ipBase&=netmask; //ip säubern //Pinging uint countIpAdresses=((1u<<netmaskBits)-1u); for(uint i=1; i<countIpAdresses; i++) { Ping p=new Ping(); //Event handler p.PingCompleted+=(object sender, PingCompletedEventArgs e) => { IPAddress ipFromReply=(IPAddress)e.UserState; if(e.Reply!=null&&e.Reply.Status==IPStatus.Success) { if(resolveNames) //resolveNames { string name; try { IPHostEntry hostEntry=Dns.GetHostEntry(ipFromReply); name=hostEntry.HostName; } catch(SocketException) { name=""; } ret.Add(new NetworkEntry(ipFromReply, e.Reply.RoundtripTime, name)); } else { ret.Add(new NetworkEntry(ipFromReply, e.Reply.RoundtripTime)); } } else if(e.Reply==null) { if(!onlyUpDevices) { ret.Add(new NetworkEntry(ipFromReply, 0, "", false)); } } countdown.Signal(); }; uint ipAsUInt=ipBase+i; IPAddress ipAdress=new IPAddress(0xFFFFFFFF&(IPAddress.HostToNetworkOrder(ipAsUInt)>>32)); countdown.AddCount(); p.SendAsync(ipAdress, timeout, ipAdress); } //Wait countdown.Signal(); countdown.Wait(); return ret; }
private void DownloadZipItems(List<ItemStatus> items) { var todo = items.Where(e => e.RequireDownload && !string.IsNullOrEmpty(e.ZipUrl)).ToList(); if (todo.Count == 0) return; #if PARALLEL CountdownEvent countdown = new CountdownEvent(1); foreach (var item in todo) { var cli = new WebClient(); cli.DownloadFileCompleted += OnDownloadZipItemCompleted; Utils.WriteLine("Downloading " + item.ZipUrl + " ..."); countdown.AddCount(1); var file = Path.Combine(launcher.WorkshopFolder, item.FolderName + ".zip"); File.Delete(file); cli.DownloadFileAsync(new Uri(item.ZipUrl), file, new Tuple<string, ItemStatus, CountdownEvent>(file, item, countdown)); } countdown.Signal(); countdown.Wait(); #else int i = 0; foreach (var item in todo) { ++i; Utils.Write(item.ZipUrl + " (" + i + "/" + todo.Count + ") ... "); var dir = Path.Combine(launcher.WorkshopFolder, item.FolderName); DateTime remoteDate; using (var cli = new HttpClient()) { var req = new HttpRequestMessage(); req.Method = HttpMethod.Head; req.RequestUri = new Uri(item.ZipUrl); var task = cli.SendAsync(req); if (!task.Wait(1000)) { Utils.WriteLine("^1timeout^7"); continue; } remoteDate = GetDateHeader(task.Result); } var localDate = File.GetLastWriteTimeUtc(dir); if (remoteDate != DateTime.MinValue && Directory.Exists(dir) && Math.Abs((remoteDate - localDate).TotalSeconds) < 1) { Utils.WriteLine("up-to-date"); continue; } Utils.WriteLine("downloading"); var file = dir + ".zip"; File.Delete(file); var wc = new WebClient(); AsyncCompletedEventArgs args; try { wc.DownloadFile(new Uri(item.ZipUrl), file); args = new AsyncCompletedEventArgs(null, false, new Tuple<string, ItemStatus, CountdownEvent, DateTime>(file, item, null, remoteDate)); } catch (Exception ex) { args = new AsyncCompletedEventArgs(ex, false, new Tuple<string, ItemStatus, CountdownEvent, DateTime>(file, item, null, remoteDate)); } OnDownloadZipItemCompleted(wc, args); } #endif }
public static void Scanner() { //Get's preferred outbound IP address string localIP; using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0)) { socket.Connect("10.0.2.4", 65530); IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint; localIP = endPoint.Address.ToString(); } //Console.WriteLine(localIP); var bytes = IPAddress.Parse(localIP).GetAddressBytes(); bytes[3] = 0; IPAddress ipAddress = new IPAddress(bytes); var IPaddress1 = IPAddress.Parse(localIP).GetAddressBytes()[0].ToString() + "." + IPAddress.Parse(localIP).GetAddressBytes()[1].ToString() + "." + IPAddress.Parse(localIP).GetAddressBytes()[2].ToString() + "."; // Console.WriteLine(bytes); //Console.WriteLine(ipAddress); //Console.WriteLine(IPaddress1); //Console.ReadLine(); //Console.WriteLine("Scanning Network"); countdown = new CountdownEvent(1); Stopwatch sw = new Stopwatch(); sw.Start(); //string ipBase = "10.0.0."; for (int i = 1; i < 255; i++) { string ip = IPaddress1 + i.ToString(); Ping p = new Ping(); p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted); countdown.AddCount(); p.SendAsync(ip, 100, ip); } countdown.Signal(); countdown.Wait(); sw.Stop(); TimeSpan span = new TimeSpan(sw.ElapsedTicks); var list = strings.Keys.ToList(); list.Sort(); }
/// <summary> /// Повикува Update на секој објект во посебен thread. Се користи ThreadPool. /// </summary> /// <param name="gameObjects"></param> private void UpdateObjectsMT(IList<IGameObject> gameObjects) { //CountdownEvent /* http://msdn.microsoft.com/en-us/library/dd997365.aspx */ //не може паралелно да се одвива оваа операција //паралелен дел using (CountdownEvent e = new CountdownEvent(1)) { // fork work: foreach (IGameObject obj in gameObjects) { // Dynamically increment signal count. e.AddCount(); ThreadPool.QueueUserWorkItem(delegate(object gameObject) { try { UpdateObject((IGameObject)gameObject); } finally { e.Signal(); } }, obj); } e.Signal(); // The first element could be run on this thread. // Join with work. e.Wait(); } InitQuadTree(gameObjects); InitCollisionArguments(gameObjects); //паралелен дел using (CountdownEvent e = new CountdownEvent(1)) { // fork work: foreach (IGameObject obj in gameObjects) { // Dynamically increment signal count. e.AddCount(); ThreadPool.QueueUserWorkItem(delegate(object gameObject) { try { CheckForCollisions((IGameObject)gameObject); } finally { e.Signal(); } }, obj); } e.Signal(); // The first element could be run on this thread. // Join with work. e.Wait(); } //паралелен дел using (CountdownEvent e = new CountdownEvent(1)) { // fork work: foreach (IGameObject obj in gameObjects) { // Dynamically increment signal count. e.AddCount(); ThreadPool.QueueUserWorkItem(delegate(object gameObject) { try { PassCollisionArgumentsToObject((IGameObject)gameObject); } finally { e.Signal(); } }, obj); } e.Signal(); // The first element could be run on this thread. // Join with work. e.Wait(); } }
// Validates init, set, reset state transitions. private static bool RunCountdownEventTest0_StateTrans(int initCount, int increms, bool takeAllAtOnce) { TestHarness.TestLog("* RunCountdownEventTest0_StateTrans(initCount={0}, increms={1}, takeAllAtOnce={2})", initCount, increms, takeAllAtOnce); CountdownEvent ev = new CountdownEvent(initCount); // Check initial count. if (ev.InitialCount != initCount) { TestHarness.TestLog(" > error: initial count wrong, saw {0} expected {1}", ev.InitialCount, initCount); return false; } // Increment (optionally). for (int i = 0; i < increms; i++) { ev.AddCount(); if (ev.CurrentCount != initCount + i + 1) { TestHarness.TestLog(" > error: after incrementing, count is wrong, saw {0}, expect {1}", ev.CurrentCount, initCount + i + 1); return false; } } // Decrement until it hits 0. if (takeAllAtOnce) { ev.Signal(initCount + increms); } else { for (int i = 0; i < initCount + increms; i++) { if (ev.IsSet) { TestHarness.TestLog(" > error: latch is set after {0} signals", i); return false; } ev.Signal(); } } // Check the status. if (!ev.IsSet) { TestHarness.TestLog(" > error: latch was not set after all signals received"); return false; } if (ev.CurrentCount != 0) { TestHarness.TestLog(" > error: latch count wasn't 0 after all signals received"); return false; } // Now reset the event and check its count. ev.Reset(); if (ev.CurrentCount != ev.InitialCount) { TestHarness.TestLog(" > error: latch count wasn't correctly reset"); return false; } return true; }
public void Dispose () { var ce = new CountdownEvent (1); ce.Dispose (); Assert.AreEqual (1, ce.CurrentCount, "#0a"); Assert.AreEqual (1, ce.InitialCount, "#0b"); Assert.IsFalse (ce.IsSet, "#0c"); try { ce.AddCount (); Assert.Fail ("#1"); } catch (ObjectDisposedException) { } try { ce.Reset (); Assert.Fail ("#2"); } catch (ObjectDisposedException) { } try { ce.Signal (); Assert.Fail ("#3"); } catch (ObjectDisposedException) { } try { ce.TryAddCount (); Assert.Fail ("#4"); } catch (ObjectDisposedException) { } try { ce.Wait (5); Assert.Fail ("#4"); } catch (ObjectDisposedException) { } try { var v = ce.WaitHandle; Assert.Fail ("#5"); } catch (ObjectDisposedException) { } }
public static void RunCountdownEventTest2_Exceptions() { CountdownEvent cde = null; Assert.Throws<ArgumentOutOfRangeException>(() => cde = new CountdownEvent(-1)); // Failure Case: Constructor didn't throw AORE when -1 passed cde = new CountdownEvent(1); Assert.Throws<ArgumentOutOfRangeException>(() => cde.Signal(0)); // Failure Case: Signal didn't throw AORE when 0 passed cde = new CountdownEvent(0); Assert.Throws<InvalidOperationException>(() => cde.Signal()); // Failure Case: Signal didn't throw IOE when the count is zero cde = new CountdownEvent(1); Assert.Throws<InvalidOperationException>(() => cde.Signal(2)); // Failure Case: Signal didn't throw IOE when the signal count > current count Assert.Throws<ArgumentOutOfRangeException>(() => cde.AddCount(0)); // Failure Case: AddCount didn't throw AORE when 0 passed cde = new CountdownEvent(0); Assert.Throws<InvalidOperationException>(() => cde.AddCount(1)); // Failure Case: AddCount didn't throw IOE when the count is zero cde = new CountdownEvent(int.MaxValue - 10); Assert.Throws<InvalidOperationException>(() => cde.AddCount(20)); // Failure Case: AddCount didn't throw IOE when the count > int.Max cde = new CountdownEvent(2); Assert.Throws<ArgumentOutOfRangeException>(() => cde.Reset(-1)); // Failure Case: Reset didn't throw AORE when the count is zero Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(-2)); // Failure Case: Wait(int) didn't throw AORE when the totalmilliseconds < -1 Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.FromDays(-1))); // Failure Case: FAILED. Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1 Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.MaxValue)); // Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.FromDays(-1), new CancellationToken())); // Failure Case: Wait(TimeSpan) didn't throw AORE when the totalmilliseconds < -1 Assert.Throws<ArgumentOutOfRangeException>(() => cde.Wait(TimeSpan.MaxValue, new CancellationToken())); // Failure Case: Wait(TimeSpan, CancellationToken) didn't throw AORE when the totalmilliseconds > int.max cde.Dispose(); Assert.Throws<ObjectDisposedException>(() => cde.Wait()); // Failure Case: Wait() didn't throw ODE after Dispose }
private void ExecuteThreadedCompilePass(int threads) { using (var finished = new CountdownEvent(1)) { for (int threadID = 0; threadID < threads; threadID++) { finished.AddCount(); int tid = threadID + 1; ThreadPool.QueueUserWorkItem( new WaitCallback(delegate { //try //{ CompileWorker(tid); //} //catch (Exception e) //{ // this.CompilerTrace.NewCompilerTraceEvent(CompilerEvent.Exception, e.ToString(), threadID); //} //finally //{ finished.Signal(); //} } )); } finished.Signal(); finished.Wait(); } }
// Validates init, set, reset state transitions. private static void RunCountdownEventTest0_StateTrans(int initCount, int increms, bool takeAllAtOnce) { string methodParameters = string.Format("RunCountdownEventTest0_StateTrans(initCount={0}, increms={1}, takeAllAtOnce={2})", initCount, increms, takeAllAtOnce); CountdownEvent ev = new CountdownEvent(initCount); // Check initial count. if (ev.InitialCount != initCount) { Debug.WriteLine(methodParameters); Assert.True(false, string.Format(" > error: initial count wrong, saw {0} expected {1}", ev.InitialCount, initCount)); } // Increment (optionally). for (int i = 0; i < increms; i++) { ev.AddCount(); if (ev.CurrentCount != initCount + i + 1) { Debug.WriteLine(methodParameters); Assert.True(false, string.Format(" > error: after incrementing, count is wrong, saw {0}, expect {1}", ev.CurrentCount, initCount + i + 1)); } } // Decrement until it hits 0. if (takeAllAtOnce) { ev.Signal(initCount + increms); } else { for (int i = 0; i < initCount + increms; i++) { if (ev.IsSet) { Debug.WriteLine(methodParameters); Assert.True(false, string.Format(" > error: latch is set after {0} signals", i)); } ev.Signal(); } } // Check the status. if (!ev.IsSet) { Debug.WriteLine(methodParameters); Assert.True(false, string.Format(" > error: latch was not set after all signals received")); } if (ev.CurrentCount != 0) { Debug.WriteLine(methodParameters); Assert.True(false, string.Format(" > error: latch count wasn't 0 after all signals received")); } // Now reset the event and check its count. ev.Reset(); if (ev.CurrentCount != ev.InitialCount) { Debug.WriteLine(methodParameters); Assert.True(false, string.Format(" > error: latch count wasn't correctly reset")); } }
public void Execute() { // // CountdownEventクラスには、以下のメソッドが存在する。 // ・AddCountメソッド // ・Resetメソッド // AddCountメソッドは、CountdownEventの内部カウントをインクリメントする。 // Resetメソッドは、現在の内部カウントをリセットする。 // // どちらのメソッドも、Int32を引数に取るオーバーロードが用意されており // 指定した数を設定することも出来る。 // // 尚、AddCountメソッドを利用する際の注意点として // 既に内部カウントが0の状態でAddCountを実行すると例外が発生する。 // つまり、既にIsSetがTrue(シグナル状態)でAddCountするとエラーとなる。 // // // 内部カウントが0の状態で、AddCountしてみる. // using (var cde = new CountdownEvent(0)) { // 初期の状態を表示. PrintCurrentCountdownEvent(cde); try { // // 既にシグナル状態の場合に、さらにAddCountしようとすると例外が発生する. // cde.AddCount(); } catch (InvalidOperationException invalidEx) { Output.WriteLine("*** {0} ***", invalidEx.Message); } // 現在の状態を表示. PrintCurrentCountdownEvent(cde); } Output.WriteLine(""); using (var cde = new CountdownEvent(1)) { // 初期の状態を表示. PrintCurrentCountdownEvent(cde); // // 10個の別処理を実行する. // それぞれの内部処理にてランダムでSLEEPして、終了タイミングをバラバラに設定. // Output.WriteLine("別処理開始・・・"); for (var i = 0; i < 10; i++) { Task.Factory.StartNew(TaskProc, cde); } do { // 現在の状態を表示. PrintCurrentCountdownEvent(cde, "t"); Thread.Sleep(TimeSpan.FromSeconds(2)); } while (cde.CurrentCount != 1); Output.WriteLine("・・・別処理終了"); // // 待機. // Output.WriteLine("メインスレッドにて最後のカウントをデクリメント"); cde.Signal(); cde.Wait(); // 現在の状態を表示. PrintCurrentCountdownEvent(cde); Output.WriteLine(""); // // 内部カウントをリセット. // Output.WriteLine("内部カウントをリセット"); cde.Reset(); // 現在の状態を表示. PrintCurrentCountdownEvent(cde); // // 待機. // Output.WriteLine("メインスレッドにて最後のカウントをデクリメント"); cde.Signal(); cde.Wait(); // 現在の状態を表示. PrintCurrentCountdownEvent(cde); } }
/// <summary> /// Receives the messages in an asynchronous loop and closes the session once there are no more messages. /// </summary> private void ReceiveMessagesAndCloseSession(MessageSession session, CancellationToken cancellationToken) { CountdownEvent unreleasedMessages = new CountdownEvent(1); Action<bool> closeSession = (bool success) => { Action doClose = () => { try { unreleasedMessages.Signal(); if (!unreleasedMessages.Wait(15000, cancellationToken)) { Trace.TraceWarning("Waited for pending unreleased messages before closing session in subscription {0} but they did not complete in time", this.subscription); } } catch (OperationCanceledException) { } finally { unreleasedMessages.Dispose(); } this.receiveRetryPolicy.ExecuteAction( cb => session.BeginClose(cb, null), session.EndClose, () => { this.instrumentation.SessionEnded(); if (success) { this.dynamicThrottling.NotifyWorkCompleted(); } else { this.dynamicThrottling.NotifyWorkCompletedWithError(); } }, ex => { this.instrumentation.SessionEnded(); Trace.TraceError("An unrecoverable error occurred while trying to close a session in subscription {1}:\r\n{0}", ex, this.subscription); this.dynamicThrottling.NotifyWorkCompletedWithError(); }); }; if (this.requiresSequentialProcessing) { doClose.Invoke(); } else { // Allow some time for releasing the messages before closing. Also, continue in a non I/O completion thread in order to block. TaskEx.Delay(200).ContinueWith(t => doClose()); } }; // Declare an action to receive the next message in the queue or closes the session if cancelled. Action receiveNext = null; // Declare an action acting as a callback whenever a non-transient exception occurs while receiving or processing messages. Action<Exception> recoverReceive = null; // Declare an action responsible for the core operations in the message receive loop. Action receiveMessage = (() => { // Use a retry policy to execute the Receive action in an asynchronous and reliable fashion. this.receiveRetryPolicy.ExecuteAction ( cb => { // Start receiving a new message asynchronously. // Does not wait for new messages to arrive in a session. If no further messages we will just close the session. session.BeginReceive(TimeSpan.Zero, cb, null); }, // Complete the asynchronous operation. This may throw an exception that will be handled internally by retry policy. session.EndReceive, msg => { // Process the message once it was successfully received // Check if we actually received any messages. if (msg != null) { var roundtripStopwatch = Stopwatch.StartNew(); long schedulingElapsedMilliseconds = 0; long processingElapsedMilliseconds = 0; unreleasedMessages.AddCount(); Task.Factory.StartNew(() => { var releaseAction = MessageReleaseAction.AbandonMessage; try { this.instrumentation.MessageReceived(); schedulingElapsedMilliseconds = roundtripStopwatch.ElapsedMilliseconds; // Make sure the process was told to stop receiving while it was waiting for a new message. if (!cancellationToken.IsCancellationRequested) { try { try { // Process the received message. releaseAction = this.InvokeMessageHandler(msg); processingElapsedMilliseconds = roundtripStopwatch.ElapsedMilliseconds - schedulingElapsedMilliseconds; this.instrumentation.MessageProcessed(releaseAction.Kind == MessageReleaseActionKind.Complete, processingElapsedMilliseconds); } catch { processingElapsedMilliseconds = roundtripStopwatch.ElapsedMilliseconds - schedulingElapsedMilliseconds; this.instrumentation.MessageProcessed(false, processingElapsedMilliseconds); throw; } } finally { if (roundtripStopwatch.Elapsed > TimeSpan.FromSeconds(45)) { this.dynamicThrottling.Penalize(); } } } } finally { // Ensure that any resources allocated by a BrokeredMessage instance are released. if (this.requiresSequentialProcessing) { this.ReleaseMessage(msg, releaseAction, () => { receiveNext(); }, () => { closeSession(false); }, unreleasedMessages, processingElapsedMilliseconds, schedulingElapsedMilliseconds, roundtripStopwatch); } else { // Receives next without waiting for the message to be released. this.ReleaseMessage(msg, releaseAction, () => { }, () => { this.dynamicThrottling.Penalize(); }, unreleasedMessages, processingElapsedMilliseconds, schedulingElapsedMilliseconds, roundtripStopwatch); receiveNext.Invoke(); } } }); } else { // no more messages in the session, close it and do not continue receiving closeSession(true); } }, ex => { // Invoke a custom action to indicate that we have encountered an exception and // need further decision as to whether to continue receiving messages. recoverReceive.Invoke(ex); }); }); // Initialize an action to receive the next message in the queue or closes the session if cancelled. receiveNext = () => { if (!cancellationToken.IsCancellationRequested) { // Continue receiving and processing new messages until told to stop. receiveMessage.Invoke(); } else { closeSession(true); } }; // Initialize a custom action acting as a callback whenever a non-transient exception occurs while receiving or processing messages. recoverReceive = ex => { // Just log an exception. Do not allow an unhandled exception to terminate the message receive loop abnormally. Trace.TraceError("An unrecoverable error occurred while trying to receive a new message from subscription {1}:\r\n{0}", ex, this.subscription); // Cannot continue to receive messages from this session. closeSession(false); }; // Start receiving messages asynchronously for the session. receiveNext.Invoke(); }
private void FindMapsInDir(string path, CountdownEvent cntDwn) { var dirs = Directory.EnumerateDirectories(path); foreach(string d in dirs) { cntDwn.AddCount(); ThreadPool.QueueUserWorkItem(o => FindMapsInDir(d, cntDwn)); } var bzns = Directory.EnumerateFiles(path, "*.bzn"); foreach(string b in bzns) { Map m = LoadMap(b.Substring(0, b.LastIndexOf('.'))); lock (MAPS_LOCK) { if(m != null) maps.Add(m); } } cntDwn.Signal(); }
/// <summary> /// Ping để tìm kiếm host đang onl /// </summary> /// <param name="ipBase"></param> public static void PingToFind(String ipBase) { countdown = new CountdownEvent(1); for (int i = 1; i < 255; i++) { string ip = ipBase + i.ToString(); Ping p = new Ping(); p.PingCompleted += new PingCompletedEventHandler(p_PingCompleted); countdown.AddCount(); p.SendAsync(ip, 100, ip); } countdown.Signal(); countdown.Wait(); }
public void InitialTestCase() { var evt = new CountdownEvent (5); Assert.AreEqual(5, evt.InitialCount, "#1"); evt.AddCount(); evt.Signal(3); Assert.AreEqual(5, evt.InitialCount, "#2"); }
public void CurrentCountTestCase() { var evt = new CountdownEvent (5); Assert.AreEqual(5, evt.CurrentCount, "#1"); evt.AddCount(); Assert.AreEqual(6, evt.CurrentCount, "#2"); evt.TryAddCount(2); Assert.AreEqual(8, evt.CurrentCount, "#3"); evt.Signal(4); Assert.AreEqual(4, evt.CurrentCount, "#4"); evt.Reset(); Assert.AreEqual(5, evt.CurrentCount, "#5"); }
private static void DoSomeCrawlingAndIndexing(int approxSites) { var dbPages = database.GetAllPages(). Select(p => new PrettyURL(p.url)); var seed = dbPages.Count() > 0 ? dbPages : new PrettyURL[] { new PrettyURL("newz.dk"), new PrettyURL("aau.dk"), new PrettyURL("politikken.dk") }; Crawler.SitesToCrawl = approxSites; CountdownEvent CTE = new CountdownEvent(1); var crawler = new Crawler(numFrontQueues, numBackQueues, timeBetweenHits, maxRobotAge, seed, ToBeIndexedQueue, CTE); var indexer = new MainIndexer(stopWords, charsToRemove, ToBeIndexedQueue, CTE); Thread crawlerThread = new Thread(crawler.Crawl); CTE.AddCount(); Thread indexerThread = new Thread(() => indexer.CreateInverseIndexWriteToDB(false)); CTE.AddCount(); crawlerThread.Start(); indexerThread.Start(); CTE.Signal(); CTE.Wait(); }
// buffer layer private void bufferButton_Click(object sender, EventArgs e) { toolBuilder.addHeader("Buffer"); // textbox for buffer distance TextBox distBox = toolBuilder.addTextboxWithCaption("Distance (m):"); // textbox for new layername TextBox nameBox = toolBuilder.addTextboxWithCaption("New layername:"); // label for errors Label errorLabel = toolBuilder.addErrorLabel(); // button for performing buffer Button selectButton = toolBuilder.addButton("Buffer", (Layer l) => { double dist = 0; // buffer does not work on lat-long projections if (SRS.IsLatLong) { toolBuilder.setError("Incompatible SRS"); return; } // distance must be a number if (!double.TryParse(distBox.Text, out dist)) { toolBuilder.setError("Not a number"); return; } // user must give new layer name if (nameBox.Text.Length == 0) { toolBuilder.setError("Provide a name"); return; } // create new layer Layer newl = new Layer(nameBox.Text); newl.DataTable = l.DataTable; List<Feature> flist = l.Features.Values.ToList(); // initialise progress bar progressLabel.Text = "Buffering"; progressBar.Minimum = 0; progressBar.Maximum = flist.Count; // threadsafe list of new features ConcurrentBag<Feature> newFeatures = new ConcurrentBag<Feature>(); BackgroundWorker bw = new BackgroundWorker(); bw.WorkerReportsProgress = true; // perform buffering in other thread bw.DoWork += (object wsender, DoWorkEventArgs we) => { using (var finished = new CountdownEvent(1)) { // for each feature for (int i = 0; i < flist.Count; i++) { // add the task to buffer a feature to a thread pool finished.AddCount(); Feature capture = flist[i]; ThreadPool.QueueUserWorkItem((state) => { // get feature Feature f = capture; // add buffered feature newFeatures.Add(new Feature(f.Geometry.Buffer(dist), f.ID)); bw.ReportProgress(i); finished.Signal(); }, null); } finished.Signal(); finished.Wait(); } bw.ReportProgress(-1); // add all buffered features to layer foreach(Feature f in newFeatures) { newl.addFeature(f); bw.ReportProgress(1); } newl.calculateBoundingBox(); newl.createQuadTree(); }; bw.RunWorkerCompleted += (object wsender, RunWorkerCompletedEventArgs we) => { // reset progress bar progressBar.Value = 0; progressLabel.Text = ""; // add and zoom newly made layer Layers.Insert(0, newl); layerList.SelectedItem = newl; }; bw.ProgressChanged += (object wsender, ProgressChangedEventArgs we) => { // update progress bar and progress label if (we.ProgressPercentage == -1){ progressBar.Value = 0; progressLabel.Text = "Creating spatial index"; } else progressBar.Value += 1; }; bw.RunWorkerAsync(); }); toolBuilder.resetAction = (Layer l) => { if (SRS.IsLatLong) toolBuilder.setError("Incompatible SRS"); nameBox.Text = (l == null) ? "" : l.Name + "_buffer"; }; toolBuilder.reset(); }
protected void ExecuteLevel(ConcurrentQueue<Computation> computationsOfLevel) { //int reqs = 0; //int prov = 0; //foreach (var item in computationsOfLevel) //{ // var pc = item.Context as ParallelComputationContext; // reqs += pc.transformationRequirements; // prov += pc.dependentContexts; //} //Console.WriteLine("{0} computations provided, {1} needed", prov, reqs); using (var countEvent = new CountdownEvent(1)) { while (true) { Computation item; if (computationsOfLevel.TryDequeue(out item)) { var cc = item.Context as ParallelComputationContext; if (cc != null) { countEvent.AddCount(); cc.RunTransform(() => { item.Transform(); countEvent.Signal(); }); } else { countEvent.Signal(); countEvent.Wait(); item.Transform(); countEvent.Reset(); } OnComputationCompleted(new ComputationEventArgs(item)); } else { break; } } countEvent.Signal(); //Thread.Sleep(2000); //if (countEvent.CurrentCount > 0) Debugger.Break(); countEvent.Wait(); } }
static void startScan(string ipBase) { countdown = new CountdownEvent(1); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 1; i < 255; i++) { string ip = ipBase + i.ToString(); new Thread(delegate() { try { Ping p = new Ping(); p.PingCompleted += new PingCompletedEventHandler(pingDone); countdown.AddCount(); p.SendAsync(ip, 100, ip); } catch (SocketException ex) { Functions.log (string.Format("Could not contact {0}", ip), 3); } }).Start(); } countdown.Signal(); countdown.Wait(); sw.Stop(); //TimeSpan span = new TimeSpan(sw.ElapsedTicks); Functions.log(string.Format("Took {0} milliseconds. {1} hosts active.", sw.ElapsedMilliseconds, upCount), 1); }
private void RotateBricks() { QuadTree<IGameObject> quadTree = this.quadtree; List<IGameObject> area = quadtree.Query(new RectangleF(Game.VirtualGameWidth / 2 - 300, 600, 600, 600)); Vector2D center = new Vector2D(Game.VirtualGameWidth / 2, 900); if (!Game.IsMultithreadingEnabled) { foreach (IGameObject obj in area) { if (obj.ObjectType != GameObjectType.Brick) continue; RotateSingleBrick(center, obj); } } else { //паралелен дел using (CountdownEvent e = new CountdownEvent(1)) { // fork work: foreach (IGameObject obj in area) { // Dynamically increment signal count. e.AddCount(); ThreadPool.QueueUserWorkItem(delegate(object gameObject) { try { RotateSingleBrick(center, obj); } finally { e.Signal(); } }, obj); } e.Signal(); // The first element could be run on this thread. // Join with work. e.Wait(); } } }
// Adapted from // stackoverflow.com/questions/4042789/how-toget-ip-of-all-hosts-in-lan public static new string[] GetAdapterNames() { countdown = new CountdownEvent(1); List<string> networks = netBaseAddresses(); if (!networks.Contains("192.168.0.")) { networks.Add("192.168.0."); } if (!networks.Contains("192.168.222.")) { networks.Add("192.168.222."); } foreach (string network in networks) { for (int i = 1; i < 255; i++) { string ip = String.Format("{0}{1}", network, i); Ping p = new Ping(); p.PingCompleted += p_PingCompleted; countdown.AddCount(); var t = Task.Factory.StartNew(() => p.SendAsync(ip, 100, ip)); t.Wait(); } } countdown.Signal(); countdown.Wait(); IPAddresses.Sort(); return IPAddresses.ToArray(); }
static async Task Main(string[] args) { // Initialize a queue and a CountdownEvent ConcurrentQueue <int> queue = new ConcurrentQueue <int>(Enumerable.Range(0, 10000)); System.Threading.CountdownEvent cde = new System.Threading.CountdownEvent(10000); // initial count = 10000 // This is the logic for all queue consumers Action consumer = () => { int local; // decrement CDE count once for each element consumed from queue while (queue.TryDequeue(out local)) { cde.Signal(); } }; // Now empty the queue with a couple of asynchronous tasks Task t1 = Task.Factory.StartNew(consumer); Task t2 = Task.Factory.StartNew(consumer); // And wait for queue to empty by waiting on cde cde.Wait(); // will return when cde count reaches 0 Console.WriteLine("Done emptying queue. InitialCount={0}, CurrentCount={1}, IsSet={2}", cde.InitialCount, cde.CurrentCount, cde.IsSet); // Proper form is to wait for the tasks to complete, even if you that their work // is done already. await Task.WhenAll(t1, t2); // Resetting will cause the CountdownEvent to un-set, and resets InitialCount/CurrentCount // to the specified value cde.Reset(10); // AddCount will affect the CurrentCount, but not the InitialCount cde.AddCount(2); Console.WriteLine("After Reset(10), AddCount(2): InitialCount={0}, CurrentCount={1}, IsSet={2}", cde.InitialCount, cde.CurrentCount, cde.IsSet); // Now try waiting with cancellation CancellationTokenSource cts = new CancellationTokenSource(); cts.Cancel(); // cancels the CancellationTokenSource try { cde.Wait(cts.Token); } catch (OperationCanceledException) { Console.WriteLine("cde.Wait(preCanceledToken) threw OCE, as expected"); } finally { cts.Dispose(); } // It's good to release a CountdownEvent when you're done with it. cde.Dispose(); Console.ReadLine(); }