public void TestDelete() { FileInfo file = new FileInfo(@"d:\X16-42552VS2010UltimTrial1.txt"); AutoResetEvent are = new AutoResetEvent(false); string key = null; HttpCommunicate.Upload(file, (result, warning) => { Console.WriteLine("result:" + result); key = result + ""; are.Set(); }, error => { Console.WriteLine("error:" + error); are.Set(); }); are.WaitOne(); are.Reset(); FileDeletePackage package = new FileDeletePackage(); package.key = key; HttpCommunicate.Request(package, (result, warning) => { Console.WriteLine("file:" + result); are.Set(); }, error => { Console.WriteLine("error:" + error); are.Set(); }); are.WaitOne(); }
/* public void Fill(int x, int y) * { * if (bTextMode) throw new RuntimeError(SimulatorMessage.NOT_ALLOWED_IN_TEXT_MODE,-1); * lock(this) * { * Brush brush = new SolidBrush(GraphPen.Color); * System.Drawing.Region points = {new System.Drawing.Region( * ((float)x,(float) y)}; * graphics.FillRegion (brush, points); * bUglyBugFixing = true; * this.Invalidate(); * } * }*/ #endregion #endregion #region Input #region text mode /// <summary> /// read one char from buffer, if it empty wait until key press /// </summary> /// <returns>the key's value</returns> public byte getchar() { if (!bTextMode) { caretThread.Abort(); throw new RuntimeError(SimulatorMessage.NOT_ALLOWED_IN_GRAPH_MODE, -1); } byte res; bNowInInputFunction = true; if (InputBuffer.Size == 0) { if (_sInputFileName != "") { return(0xFF); } else { eWaitForInput.WaitOne(); } } if (bNowExiting) { return(0xFF); // magic number - EOF } iBufferPrinted--; res = InputBuffer[0]; InputBuffer = InputBuffer.SubBlock(1); return(res); }
public void describe_custom_gossip_message_factory_creating_different_message_types() { var clusterConfig = new GossipClusterConfig { ClusterKey = Encoding.UTF8.GetBytes("ClusterKey") }; var nodeConfig1 = new GossipNodeConfig(new IPEndPoint(IPAddress.Loopback, NodePort1)); var nodeConfig2 = new GossipNodeConfig(new IPEndPoint(IPAddress.Loopback, NodePort2)); var message1 = new GossipMessage1(); var message2 = new GossipMessage2(); GossipMessageFactory.CreateMessage += CreateMessage; using (var node1 = new GossipNode(nodeConfig1, clusterConfig)) using (var node2 = new GossipNode(nodeConfig2, clusterConfig)) { var received = new AutoResetEvent(false); GossipMessage receivedMsg = null; node1.OnMessageReceived += (node, conn, msg) => { receivedMsg = msg; received.Set(); }; node1.StartListening(); node2.StartListening(); node1.Cluster.Join(new GossipClusterMember(nodeConfig1.NodeId, nodeConfig2, node2.Authenticator)); node2.Cluster.Join(new GossipClusterMember(nodeConfig2.NodeId, nodeConfig1, node1.Authenticator)); node2.Cluster.BroadcastMessage(message1); if (!received.WaitOne(Timeout)) Assert.Fail(); Assert.IsInstanceOf<GossipMessage1>(receivedMsg); node2.Cluster.BroadcastMessage(message2); if (!received.WaitOne(Timeout)) Assert.Fail(); Assert.IsInstanceOf<GossipMessage2>(receivedMsg); } }
static void Main(string[] args) { AutoResetEvent syncEvent = new AutoResetEvent(false); // create the workflow app and add handlers for the Idle and Completed actions WorkflowApplication app = new WorkflowApplication(new Sequence1()); app.Idle = delegate(WorkflowApplicationIdleEventArgs e) { syncEvent.Set(); }; app.Completed = delegate(WorkflowApplicationCompletedEventArgs e) { syncEvent.Set(); }; // start the application app.Run(); syncEvent.WaitOne(); // read some text from the console and resume the readText bookmark (created in the first WaitForInput activity) string text = Console.ReadLine(); app.ResumeBookmark("readText", text); syncEvent.WaitOne(); // read some text from the console, convert it to number, and resume the readNumber bookmark (created in the second WaitForInput activity) int number = ReadNumberFromConsole(); app.ResumeBookmark("readNumber", number); syncEvent.WaitOne(); Console.WriteLine(""); Console.WriteLine("Press [ENTER] to exit..."); Console.ReadLine(); }
private void CreateMainTask() { taskSimpleScheduler = new TaskSimpleScheduler(); autoResetEvent.Reset(); taskSimpleScheduler.StartNewTask("模拟业务", () => { if (!this.IsStartSimulator) { return; } // 心跳 this.EquDber.Execute("update " + EntityReflectionUtil.GetTableName <EquQCJXCYJSignal>() + " set TagValue=@TagValue where TagName=@TagName", new { TagName = GlobalVars.EquHeartbeatName, TagValue = DateTime.Now.ToString() }); // 控制命令 EquQCJXCYJSampleCmd qCJXCYJSampleCmd = this.EquDber.Entity <EquQCJXCYJSampleCmd>("where DataFlag=0 order by CreateDate desc"); if (qCJXCYJSampleCmd != null) { CmdHandle(qCJXCYJSampleCmd); autoResetEvent.WaitOne(); } // 卸样命令 EquQCJXCYJUnloadCmd qCJXCYJUnloadCmd = this.EquDber.Entity <EquQCJXCYJUnloadCmd>("where DataFlag=0 order by CreateDate desc"); if (qCJXCYJUnloadCmd != null) { CmdHandle(qCJXCYJUnloadCmd); autoResetEvent.WaitOne(); } }, 3000); }
public void Should_Receive_Many_Envelopes_When_Filter_Returns_True() { InMemoryEnvelopeBus bus = new InMemoryEnvelopeBus(); AutoResetEvent waitHandle = new AutoResetEvent(false); Envelope env = new Envelope(); env.Payload = Encoding.UTF8.GetBytes("Test"); Mock<IRegistration> reg = _mocker.Create<IRegistration>(); reg.Setup(r => r.Filter).Returns(new Predicate<Envelope>(e => true)); reg.Setup(r => r.Handle(env)).Callback(() => waitHandle.Set()); bus.Register(reg.Object); bus.Send(env); waitHandle.WaitOne(5000); bus.Send(env); waitHandle.WaitOne(5000); bus.Send(env); waitHandle.WaitOne(5000); bus.Send(env); waitHandle.WaitOne(5000); bus.Send(env); waitHandle.WaitOne(5000); reg.Verify(r => r.Handle(env), Times.Exactly(5)); }
public static bool ClearMarkedPosts(ThreadMetadata thread, int timeout = CoreConstants.DEFAULT_TIMEOUT_IN_MILLISECONDS) { // create request HttpWebRequest request = AwfulWebRequest.CreateFormDataPostRequest( "http://forums.somethingawful.com/showthread.php", "application/x-www-form-urlencoded"); // begin request stream creation and wait... var signal = new AutoResetEvent(false); var result = request.BeginGetRequestStream(callback => SendClearMarkedPostRequest(callback, signal, thread), request); signal.WaitOne(); // begin response stream and wait... request = result.AsyncState as HttpWebRequest; result = request.BeginGetResponse(callback => { signal.Set(); }, request); signal.WaitOne(timeout); if (!result.IsCompleted) throw new TimeoutException(); // process the response and return status bool success = ProcessClearMarkedPostResponse(result); return success; }
public void Success() { AutoResetEvent completed = new AutoResetEvent(false); if (Socket.OSSupportsIPv4) { int port, port1; using (SocketTestServer.SocketTestServerFactory(IPAddress.Loopback, out port)) using (SocketTestServer.SocketTestServerFactory(IPAddress.Loopback, out port1)) { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnCompleted; args.UserToken = completed; args.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port); args.DisconnectReuseSocket = true; Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Assert.True(client.ConnectAsync(args)); Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection"); Assert.Equal<SocketError>(SocketError.Success, args.SocketError); client.Disconnect(true); args.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port1); Assert.True(client.ConnectAsync(args)); Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection"); Assert.Equal<SocketError>(SocketError.Success, args.SocketError); client.Dispose(); } } }
public void DisconnectAsync_Success() { AutoResetEvent completed = new AutoResetEvent(false); IPEndPoint loopback = new IPEndPoint(IPAddress.Loopback, 0); using (var server1 = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, loopback)) using (var server2 = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, loopback)) { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnCompleted; args.UserToken = completed; args.RemoteEndPoint = server1.EndPoint; args.DisconnectReuseSocket = true; using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.True(client.ConnectAsync(args)); completed.WaitOne(); Assert.Equal(SocketError.Success, args.SocketError); Assert.True(client.DisconnectAsync(args)); completed.WaitOne(); Assert.Equal(SocketError.Success, args.SocketError); args.RemoteEndPoint = server2.EndPoint; Assert.True(client.ConnectAsync(args)); completed.WaitOne(); Assert.Equal(SocketError.Success, args.SocketError); } } }
public void Test_SendToWrongPort() { IPEndPoint ep1 = new IPEndPoint (IPAddress.Parse ("10.0.0.1"), 10000); IPEndPoint ep2 = new IPEndPoint (IPAddress.Parse ("10.0.0.2"), 10000); VirtualNetwork network = new VirtualNetwork (LatencyTypes.Constant (20), 5, PacketLossType.Lossless (), 2); byte[] msg = new byte[]{0, 1, 2, 3}; try { using (AutoResetEvent done = new AutoResetEvent (false)) using (VirtualDatagramEventSocket sock1 = new VirtualDatagramEventSocket (network, ep1.Address)) using (VirtualDatagramEventSocket sock2 = new VirtualDatagramEventSocket (network, ep2.Address)) { sock1.Bind (new IPEndPoint (IPAddress.Any, ep1.Port)); sock2.Bind (new IPEndPoint (IPAddress.Any, ep2.Port)); sock1.Received += new DatagramReceiveEventHandler (delegate (object sender, DatagramReceiveEventArgs e) { done.Set (); }); sock2.Received += new DatagramReceiveEventHandler (delegate (object sender, DatagramReceiveEventArgs e) { done.Set (); }); sock1.SendTo (msg, new IPEndPoint (ep2.Address, ep2.Port + 1)); Assert.IsFalse (done.WaitOne (500)); sock2.SendTo (msg, ep1); Assert.IsTrue (done.WaitOne ()); } } finally { network.Close (); } }
public void AsyncStorageModule_InvalidKeyValue_Method() { var module = new AsyncStorageModule(); var waitHandle = new AutoResetEvent(false); var error = default(JObject); var result = default(JArray); var callback = new MockCallback(res => { error = res.Length > 0 ? (JObject)res[0] : null; result = res.Length > 1 ? (JArray)res[1] : null; waitHandle.Set(); }); var array = new[] { new[] { "5", "5", "5" }, }; module.clear(callback); Assert.IsTrue(waitHandle.WaitOne()); Assert.IsNull(error); Assert.IsNull(result); module.multiSet(array, callback); Assert.IsTrue(waitHandle.WaitOne()); Assert.AreEqual(error["message"], "Invalid Value"); Assert.IsNull(result); }
public void DispatchEventWithDispatcherQueueExceptionPort() { using (Dispatcher d = new Dispatcher ()) { var dq = new DispatcherQueue ("foo", d); var evt = new AutoResetEvent (false); var port = new Port<Exception> (); dq.UnhandledExceptionPort = port; int portPost = 0; int dispEx = 0; d.UnhandledException += delegate { ++dispEx; }; var rec = Arbiter.Receive (true, port, (e) => { ++portPost; evt.Set(); }); rec.TaskQueue = dq; rec.Execute (); dq.Enqueue (Arbiter.FromHandler (() => { throw new Exception (); })); Assert.IsTrue (evt.WaitOne (2000), "#1"); Assert.AreEqual (1, portPost, "#2"); Assert.AreEqual (0, dispEx, "#3"); dq.Enqueue (Arbiter.FromHandler (() => { throw new Exception (); })); Assert.IsTrue (evt.WaitOne (2000), "#4"); Assert.AreEqual (2, portPost, "#5"); Assert.AreEqual (0, dispEx, "#6"); } }
public void ThreadStart() { while (true) { var lTotalSec = fDelay; var lCB = fCallback; if (lTotalSec.TotalSeconds < 0) { fWaitEvent.WaitOne(); continue; } else { if (fWaitEvent.WaitOne(lTotalSec)) { continue; // don't want that } } if (fStop) { return; } if (fCallback == lCB) { lCB(null); if (!fRepeat) { fDelay = TimeSpan.FromMinutes(-1); } } } }
private static void DemoOne() { //AutoResetEvent example //AutoResetEvent 通知正在等待的线程已发生的事件。 AutoResetEvent waitHandler = new AutoResetEvent(false);//false 即非终止,未触发。 new Thread(() => { waitHandler.WaitOne(); //阻塞当前线程,等待底层内核对象收到信号。 Console.WriteLine("线程1接收到信号,开始处理。"); }).Start(); new Thread(() => { waitHandler.WaitOne(); //阻塞当前线程,等待底层内核对象收到信号。 Console.WriteLine("线程2接收到信号,开始处理。"); }).Start(); new Thread(() => { Thread.Sleep(2000); Console.WriteLine("线程3发信号"); waitHandler.Set(); //向内核对象发送信号。设置事件对象为非终止状态、false,解除阻塞。 }).Start(); //waitHandler.Close(); //释放句柄资源。 //waitHandler.Reset(); //手动设置事件为非终止状态、false,线程阻止。 Console.ReadLine(); }
public void when_receiving_message_then_can_send_new_message() { var secondReceiver = new TestableMessageReceiver(this.connectionFactory); this.sender.Send(new Message("message1")); var waitEvent = new AutoResetEvent(false); string receiver1Message = null; string receiver2Message = null; this.receiver.MessageReceived += (s, e) => { waitEvent.Set(); receiver1Message = e.Message.Body; waitEvent.WaitOne(); }; secondReceiver.MessageReceived += (s, e) => { receiver2Message = e.Message.Body; }; ThreadPool.QueueUserWorkItem(_ => { this.receiver.ReceiveMessage(); }); Assert.IsTrue(waitEvent.WaitOne(TimeSpan.FromSeconds(10))); this.sender.Send(new Message("message2")); secondReceiver.ReceiveMessage(); waitEvent.Set(); Assert.IsTrue("message1" == receiver1Message); Assert.IsTrue("message2" == receiver2Message); }
public void SendEvent_multipleEvents_OnlyTheFirstAndLastEventsAreSent() { AutoResetEvent eventSent = new AutoResetEvent(false); int numberSetByEvent = -1; SendRateLimittedEvent<int> limittedEvent = new SendRateLimittedEvent<int>(100, num => { numberSetByEvent = num; eventSent.Set(); }); limittedEvent.SendEvent(1); eventSent.WaitOne(1000); Assert.AreEqual(1, numberSetByEvent); limittedEvent.SendEvent(2); limittedEvent.SendEvent(3); limittedEvent.SendEvent(4); Assert.AreEqual(1, numberSetByEvent); limittedEvent.SendEvent(5); eventSent.WaitOne(1000); Assert.AreEqual(5, numberSetByEvent); }
void ProcessVaultMessages() { try { while (!at_vminterval.WaitOne(VaultMessageDBinterval)) { if (DataHelper.CheckSqlConnectionExists()) { DataTable dt_Messages = DataHelper.GetIncomingMessages(); if (dt_Messages.Rows.Count > 0) { foreach (DataRow dr in dt_Messages.Rows) { if (!DataHelper.ProcessIncomingMessages(Convert.ToInt64(dr["RequestID"]), dr["EventType"].ToString(), Convert.ToInt32(dr["EventID"]), dr["XmlData"].ToString(), SkipErrorMessage)) { LogManager.WriteLog("Message Proceed Failed RequestID:" + dr["RequestID"].ToString() + " EventType:" + dr["EventType"].ToString(), LogManager.enumLogLevel.Info); at_vminterval.WaitOne(VaultMessageDBinterval); break; } else { LogManager.WriteLog("Message Proceed Successfully RequestID:" + dr["RequestID"].ToString() + " EventType:" + dr["EventType"].ToString(), LogManager.enumLogLevel.Info); } } } } } } catch (Exception ex) { ExceptionManager.Publish(ex); } }
public void MessageAfterExceptionTest() { Exception e = null; AutoResetEvent even = new AutoResetEvent(false); int y = 0; var a = new Arbitr<Message, NOPMessage>( (z) => { y = 1 / z.x; even.Set(); }, (z) => { e = z; even.Set(); }); a.Send(new Message() { x = 0 }); bool completed = even.WaitOne(500); Assert.IsTrue(completed); Assert.IsNotNull(e); Assert.AreEqual(y, 0); e = null; a.Send(new Message() { x = 1 }); completed = even.WaitOne(500); Assert.IsTrue(completed); Assert.IsNull(e); Assert.AreEqual(y, 1); }
static void Main(string[] args) { // Create an event to signal the timeout count threshold in the timer callback. AutoResetEvent autoEvent = new AutoResetEvent(false); StatusChecker statusChecker = new StatusChecker(10); // Create an inferred delegate that invokes methods for the timer. TimerCallback tcb = statusChecker.CheckStatus; // Create a timer that signals the delegate to invoke CheckStatus after one second, // and every 1/4 second thereafter. Console.WriteLine("{0} Creating timer.\n", DateTime.Now.ToString("h:mm:ss.fff")); Timer stateTimer = new Timer(tcb, autoEvent, 1000, 250); // When autoEvent signals, change the period to every 1/2 second. autoEvent.WaitOne(5000, false); stateTimer.Change(0, 500); Console.WriteLine("\nChanging period.\n"); // When autoEvent signals the second time, dispose of the timer. autoEvent.WaitOne(5000, false); stateTimer.Dispose(); Console.WriteLine("\nDestroying timer."); }
/// <summary> /// Create a Pusher Client, and subscribes a user /// </summary> /// <param name="pusherServer">Server to connect to</param> /// <param name="reset">The AutoReset to control the subscription by the client</param> /// <param name="channelName">The name of the channel to subscribe to</param> /// <returns>A subscribed client</returns> public static PusherClient.Pusher CreateClient(Pusher pusherServer, AutoResetEvent reset, string channelName) { PusherClient.Pusher pusherClient = new PusherClient.Pusher(Config.AppKey, new PusherClient.PusherOptions() { Authorizer = new InMemoryAuthorizer( pusherServer, new PresenceChannelData() { user_id = "Mr Pusher", user_info = new { twitter_id = "@pusher" } }) }); pusherClient.Connected += delegate { reset.Set(); }; pusherClient.Connect(); reset.WaitOne(TimeSpan.FromSeconds(5)); var channel = pusherClient.Subscribe(channelName); channel.Subscribed += delegate { reset.Set(); }; reset.WaitOne(TimeSpan.FromSeconds(5)); return pusherClient; }
/// <summary> /// Constructs an association used by an SCP using a socket and supporting a set of services /// </summary> /// <param name="socket">The server socket to use for the association.</param> /// <param name="services">The services that this SCP supports.</param> /// <param name="hosts">The workstations that this SCP has registered with it.</param> internal Association(Socket socket, List <ServiceClass> services, Dictionary <string, ApplicationEntity> hosts) { Initialize(); lock (sentry) { number = ++serial; } //#if DEBUG // Console.WriteLine("socket {0,4} opened", number); //#endif this.hosts = hosts; foreach (ServiceClass service in services) { AddService((ServiceClass)service.Clone()); } this.socket = socket; this.State = State.Waiting; machineThread = new Thread(new ThreadStart(StateMachine)); machineThread.Name = "Association.StateMachine"; machineThread.Start(); if (!threadEvent.WaitOne(timeout, false)) { Logging.Log("Background thread not started."); } }
public void Do_Timeout() { var sw = Stopwatch.StartNew(); const int ms = 100; var i = 0; var ellapsed = 0L; var wait = new AutoResetEvent(false); Do.Timeout(() => { ellapsed = sw.ElapsedMilliseconds; i++; wait.Set(); }, ms); if (wait.WaitOne(ms * 3)) { Assert.AreEqual(1, i); Assert.IsTrue(ellapsed > ms * .9); } else { Assert.Fail("callback not executed."); } sw.Restart(); var killswitch = Do.Timeout(() => { wait.Set(); }, ms * 2); killswitch.Kill(); ellapsed = sw.ElapsedMilliseconds; Assert.IsTrue(ellapsed < ms * 2); if (wait.WaitOne(ms * 4)) { Assert.Fail("Unable to stop timeout."); } }
private static void Main(string[] args) { var taskOne = Task.Factory.StartNew(() => { Console.WriteLine("Task 1 is starting..."); Thread.Sleep(5000); AutoResetEvent.Set(); Console.WriteLine("Task 1 is completed."); }); var taskTwo = Task.Factory.StartNew(() => { Console.WriteLine("Task 2 waiting for Task 1 to complete..."); AutoResetEvent.WaitOne(); Console.WriteLine("Task 2 is started..."); Console.WriteLine("Waiting for AutoResetEvent to set..."); AutoResetEvent.WaitOne(); }); taskTwo.Wait(); // taskTwo will never complete as its waiting for autoResetEvent to set, but no thread is executing and setting it. Console.ReadLine(); }
public void TestNotifyWork() { // prepare workAction call tracking var callEvent = new AutoResetEvent(false); Func<Task> workAction = () => { callEvent.Set(); return Task.FromResult(false); }; // initialize worker using (var worker = new MockWorker(workAction)) { // verify workAction has not been called var wasCalled = callEvent.WaitOne(1000); Assert.IsFalse(wasCalled); // start worker worker.Start(); // verify workAction has not been called wasCalled = callEvent.WaitOne(1000); Assert.IsFalse(wasCalled); // notify worker worker.NotifyWork(); // verify workAction has been called wasCalled = callEvent.WaitOne(); Assert.IsTrue(wasCalled); // stop worker worker.Stop(); // verify workAction has not been called wasCalled = callEvent.WaitOne(1000); Assert.IsFalse(wasCalled); } }
public void CurrentIsVisibleAccrossThreads() { var sqlCharacters = new TestSqlCharacters(); SqlCharacters actual = null; var handle = new AutoResetEvent(false); var thread1 = new Thread(() => { SqlCharacters.Current = sqlCharacters; handle.Set(); }); var thread2 = new Thread(() => { actual = SqlCharacters.Current; handle.Set(); }); thread1.Start(); handle.WaitOne(); thread2.Start(); handle.WaitOne(); thread1.Abort(); thread2.Abort(); Assert.Same(sqlCharacters, actual); }
/// <summary>Waits for an AutoResetEvent to become signalled</summary> /// <param name="waitHandle">WaitHandle the method will wait for</param> /// <param name="ticks">Number of ticks to wait</param> /// <returns> /// True if the WaitHandle was signalled, false if the timeout was reached /// </returns> public override bool WaitOne(AutoResetEvent waitHandle, long ticks) { #if XNA_3 return waitHandle.WaitOne((int)(ticks / TicksPerMillisecond), false); #elif XBOX360 || WINDOWS_PHONE return waitHandle.WaitOne((int)(ticks / TicksPerMillisecond)); #else return waitHandle.WaitOne((int)(ticks / TicksPerMillisecond), false); #endif }
public void MultipleSet () { AutoResetEvent evt = new AutoResetEvent (true); Assert.IsTrue (evt.WaitOne (1000, false), "#1"); evt.Set (); evt.Set (); Assert.IsTrue (evt.WaitOne (1000, false), "#2"); Assert.IsFalse (evt.WaitOne (1000, false), "#3"); }
public void MultipleSet () { AutoResetEvent evt = new AutoResetEvent (true); Assertion.AssertEquals ("#01", true, evt.WaitOne (1000, false)); evt.Set (); evt.Set (); Assertion.AssertEquals ("#02", true, evt.WaitOne (1000, false)); Assertion.AssertEquals ("#03", false, evt.WaitOne (1000, false)); }
static void Main(string[] args) { string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress)); host.AddServiceEndpoint(typeof(ITest), new BasicHttpBinding(), ""); host.Open(); WriteLine("Host opened"); ChannelFactory<ITest> factory = new ChannelFactory<ITest>(new BasicHttpBinding(), new EndpointAddress(baseAddress)); ITest proxy = factory.CreateChannel(); WriteLine("Add(4, 5): {0}", proxy.Add(4, 5)); WriteLine("Add(4, 5): {0}", proxy.Add(4, 5)); AutoResetEvent evt = new AutoResetEvent(false); proxy.BeginPower(2, 64, delegate(IAsyncResult asyncResult) { WriteLine("Pow(2, 64): {0}", proxy.EndPower(asyncResult)); evt.Set(); }, null); evt.WaitOne(); proxy.BeginPower(2, 64, delegate(IAsyncResult asyncResult) { WriteLine("Pow(2, 64): {0}", proxy.EndPower(asyncResult)); evt.Set(); }, null); evt.WaitOne(); WriteLine("Reverse(\"Hello world\"): {0}", proxy.Reverse("Hello world")); WriteLine("Reverse(\"Hello world\"): {0}", proxy.Reverse("Hello world")); int i; WriteLine("TryParseInt(123): {0}, {1}", proxy.TryParseInt("123", out i), i); WriteLine("TryParseInt(123): {0}, {1}", proxy.TryParseInt("123", out i), i); proxy.BeginTryParseDouble("34.567", delegate(IAsyncResult asyncResult) { double dbl; WriteLine("TryParseDouble(34.567): {0}, {1}", proxy.EndTryParseDouble(out dbl, asyncResult), dbl); evt.Set(); }, null); evt.WaitOne(); proxy.BeginTryParseDouble("34.567", delegate(IAsyncResult asyncResult) { double dbl; WriteLine("TryParseDouble(34.567): {0}, {1}", proxy.EndTryParseDouble(out dbl, asyncResult), dbl); evt.Set(); }, null); evt.WaitOne(); WriteLine("Press ENTER to close"); Console.ReadLine(); host.Close(); }
private static void DemoTwo() { //AutoResetEvent实例初始为非终止状态 AutoResetEvent autoResetEvent = new AutoResetEvent(false); new Thread(() => { while (true) { //调用WaitOne来等待信号,并设置超时时间为5秒 bool status = autoResetEvent.WaitOne(5000); if (status) { Console.WriteLine("ThreadOne get the signal"); } else { Console.WriteLine("ThreadOne timeout(5 seconds) waiting for signal"); break; } } Console.WriteLine("ThreadOne Exit"); }).Start(); new Thread(() => { while (true) { //调用WaitOne来等待信号,并设置超时时间为5秒 bool status = autoResetEvent.WaitOne(5000); if (status) { Console.WriteLine("ThreadTwo get the signal"); } else { Console.WriteLine("ThreadTwo timeout(5 seconds) waiting for signal"); break; } } Console.WriteLine("ThreadTwo Exit"); }).Start(); Random ran = new Random(); for (int i = 0; i < 8; i++) { Thread.Sleep(ran.Next(500, 1000)); //通过Set向 AutoResetEvent 发信号以释放等待线程 Console.WriteLine("Main thread send the signal"); autoResetEvent.Set(); } // Console.ReadLine(); }
public void Queue_2 () { Console.WriteLine ("Queue_2"); var bus = new InProcessBus (); var repo = new DownloadRepositoryMock (); long total = 0; long written = 0; var wait1 = new AutoResetEvent (false); var download = new Download { Url = "url", Total = 0, Written = 0 }; repo.Insert (download); var progressmanager = new ProgressManager (bus, repo); Action<Download> progresshandle = (d) => { total = d.Total; written = d.Written; wait1.Set(); }; progressmanager.Queue (download.Url, progresshandle); download.Total = 100; download.Written = 10; progressmanager.NotifyProgress (new NotifyProgress { Url = download.Url, Download = download }); download.Written = 50; progressmanager.NotifyProgress (new NotifyProgress { Url = download.Url, Download = download }); download.Written = 100; progressmanager.NotifyProgress (new NotifyProgress { Url = download.Url, Download = download }); wait1.WaitOne (); wait1.WaitOne (); wait1.WaitOne (); Assert.AreEqual (100, written, "Written"); Assert.AreEqual (100, total, "Total"); }
public void ExecuteOnlyAfterStart() { PoolFiber fiber = new PoolFiber(); AutoResetEvent reset = new AutoResetEvent(false); fiber.Enqueue(delegate { reset.Set(); }); Assert.IsFalse(reset.WaitOne(1, false)); fiber.Start(); Assert.IsTrue(reset.WaitOne(1000, false)); fiber.Stop(); }
private void DrawRectangle() { autoResetEvent.WaitOne(); Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine(" *****"); Console.WriteLine(" *****"); Console.WriteLine(" *****"); Console.ResetColor(); autoResetEvent.Set(); }
public void BeginRequest(RequestData data, HttpAsyncCallback callback, object state) { var request = WebRequest.CreateHttp(data.Request.Url); request.Method = data.Request.Method; //data.Request.BodySize; //data.Request.Comment; //data.Request.Cookies; //data.Request.Headers; //data.Request.HeadersSize; //data.Request.HttpVersion; //data.Request.PostData; //data.Request.QueryString; var gate = new AutoResetEvent(false); if (!string.IsNullOrEmpty(data.Request.PostData.Text)) { request.BeginGetRequestStream(ar => { var postStream = request.EndGetRequestStream(ar); byte[] byteArray = Encoding.UTF8.GetBytes(data.Request.PostData.Text); postStream.Write(byteArray, 0, byteArray.Length); postStream.Flush(); gate.Set(); }, state); } else { gate.Set(); } gate.WaitOne(); var result = request.BeginGetResponse(ar => { var r = request.EndGetResponse(ar); var s = r.GetResponseStream(); var d = ReadFully(s); var txt = Encoding.UTF8.GetString(d, 0, d.Length); data.Response = new Response() { Content = new Content() { Text = txt } }; gate.Set(); }, state); gate.WaitOne(); }
public void TestRecorder() { var client = new ClientBase(new Serializer()); var recorder = new Recorder(client); recorder.Start(); var gate = new AutoResetEvent(false); Exception exception = null; FooClass result = null; Guid id = client.BeginRequest(RequestMethod.GET, "http://api.geonames.org", "/citiesJSON?north={north}&south={south}&east{east}&west={west}&lang={lang}&username={username}", new Dictionary<string, string>(), new Dictionary<string, object> { {"north",44.1}, {"south",-9.9}, {"east",-22.4}, {"west",55.2}, {"lang","de"}, {"username","demo"} }, ContentType.TEXT, ContentType.JSON, TimeSpan.FromSeconds(1), 3000, 0, ar => { try { result = client.EndRequest<FooClass>(ar); var responsetext = ar.ResponseText; } catch (Exception ex) { exception = ex; } gate.Set(); }, null); if (!gate.WaitOne(10000)) { throw new Exception("timed out"); } // verify cache has purged gate.WaitOne(3000); if (exception != null) { Assert.Fail(exception.Message); } recorder.Stop(); List<RequestInfoBase> recorded = recorder.GetRequests(); recorder.Dispose(); Assert.IsTrue(recorded.Count == 1); var recordedJson = client.Serializer.SerializeObject(recorded); List<RequestInfoBase> deserializedRecording = client.Serializer.DeserializeObject<List<RequestInfoBase>>(recordedJson); Assert.IsTrue(deserializedRecording.Count == 1); }
public static void ExecuteOnlyAfterStart(IFiber fiber) { using (fiber) using (var reset = new AutoResetEvent(false)) { fiber.Enqueue(() => reset.Set()); Assert.IsFalse(reset.WaitOne(1, false)); fiber.Start(); Assert.IsTrue(reset.WaitOne(1000, false)); } }
/// <summary> /// Queries all privileges assigned to this universe. /// </summary> /// <returns>An enumerator returning KeyValuePairs of Account and Privileges. The entry can be orphaned, when the corresponding Account is null.</returns> public IEnumerable <KeyValuePair <Account, Privileges> > QueryPrivileges() { using (System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false)) { List <KeyValuePair <uint, Privileges> > ids = new List <KeyValuePair <uint, Privileges> >(); using (Session session = Server.connection.NewSession()) { Packet packet = session.Request; packet.Command = 0x44; packet.BaseAddress = ID; Server.connection.Send(packet); Server.connection.Flush(); ThreadPool.QueueUserWorkItem(async delegate { // I hate you for forcing me to do this, microsoft. Really. packet = await session.Wait().ConfigureAwait(false); are.Set(); }); are.WaitOne(); BinaryMemoryReader reader = packet.Read(); while (reader.Size > 0) { ids.Add(new KeyValuePair <uint, Privileges>(reader.ReadUInt32(), (Privileges)reader.ReadByte())); } } Account account = null; foreach (KeyValuePair <uint, Privileges> kvp in ids) { ThreadPool.QueueUserWorkItem(async delegate { // I hate you for forcing me to do this, microsoft. Really. account = (await Server.QueryAccount(kvp.Key).ConfigureAwait(false)) ?? new Account(Server, kvp.Key); are.Set(); }); are.WaitOne(); yield return(new KeyValuePair <Account, Privileges>(account, kvp.Value)); } } }
private void EhThreadBody() { while (_keepThreadRunning) { try { ProcessInvokerQueue(); _triggeringEvent.WaitOne(_safetyIntervalTime_msec); } catch (Exception ex) { // the exception must be re-thrown on the Gui thread in order to be handled _dispatcherForReThrowingExceptions.Invoke((Action <Exception>)ReThrow, new object[] { ex }); } } // Process the invoker queue one last time ProcessInvokerQueue(); var locTriggerEvent = _triggeringEvent; if (null != locTriggerEvent) { locTriggerEvent.Dispose(); } _triggeringEvent = null; _thread = null; }
private void Keyevent_Handler() { if (IsThreadRunning) { return; } lock (syncronizer) { IsThreadRunning = true; while (true) { if (Available == false) { AvailablityHolder.WaitOne(); } if (CloseToken) { CloseToken = false; break; } if (Available) { process_keyevent(KeyeventQueue.Dequeue()); } } IsThreadRunning = false; } }
public void AutoRestEventTest() { CodeTimer.Time("AutoResetEvent(false)", () =>//无信号,可以通过WaitOne 阻塞线程的执行,通过Set发出信号唤醒等待的线程 { using (System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false)) { System.Threading.ThreadPool.QueueUserWorkItem((s) => { Thread.Sleep(1000); Console.WriteLine("Run!"); are.Set(); }); are.WaitOne(); } }); CodeTimer.Time("AutoResetEvent(true)", () =>//有信号表示终止状态,即线程属于闲置状态 { using (System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(true)) { System.Threading.ThreadPool.QueueUserWorkItem((s) => { Thread.Sleep(1000); Console.WriteLine("Not Run!"); are.Set(); }); are.WaitOne();//不会等待子线程的结束 } }); }
/// <summary> /// Method for the background thread that generates random text strings /// </summary> /// <remarks> /// <para> /// The RandomTextInputStream is often used to generate /// large texts or strings. There's an advantage to using a /// background thread to generating those texts while the /// foreground is reading from the text /// </para> /// </remarks> private void _Producer(object state) { int nowServing = 0; try { do { _randomText[nowServing] = _rtg.Generate(_maxChunkSize); _slurps++; _needData.WaitOne(); if (_isDisposed) { break; } _readyIndex = nowServing; nowServing = 1 - nowServing; _haveData.Set(); } while (true); } catch (System.Exception) { } _producerDone.Set(); }
public async Task TestMICRenderURLScopeID() { // Arrange var builder = new Client.Builder(TestSetup.app_key, TestSetup.app_secret); var client = builder.Build(); var autoEvent = new System.Threading.AutoResetEvent(false); string urlToTestForScopeID = String.Empty; var micDelegate = new KinveyMICDelegate <User>() { onError = (user) => { }, onSuccess = (error) => { }, onReadyToRender = (url) => { urlToTestForScopeID = url; autoEvent.Set(); } }; // Act User.LoginWithMIC("mytestredirectURI", micDelegate); bool signal = autoEvent.WaitOne(5000); // Assert Assert.IsTrue(signal); Assert.IsFalse(urlToTestForScopeID.Equals(string.Empty)); Assert.IsTrue(urlToTestForScopeID.Contains("scope=openid")); }
private void StartSend() { t2 = new Thread(() => { while (true) { ARE.WaitOne(Min_DelayTime); if (CTS.IsCancellationRequested) { return; } QueueItem item = null; while ((item = queue.DeQueue()) != null) { if (CTS.IsCancellationRequested) { return; } Notify(item); } } }); t2.IsBackground = true; t2.Start(); }
public int Run(PlayerOptions options) { SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); int res = Initialize(options); if (res != 0) { return(res); } if (!options.NonInteractive) { Console.WriteLine(StringResources.PressKeyToExit); Console.ReadKey(); } else { m_IsDaemon = options.Daemon; m_NonInteractiveWaitEvent = new System.Threading.AutoResetEvent(false); bool shutdown = false; while (!shutdown) { m_NonInteractiveWaitEvent.WaitOne(200); lock (m_LockObject) { shutdown = m_Shutdown; } } } Shutdown(); return(0); }
/// <summary> /// 翻车业务逻辑入口 /// </summary> private void CreateMainTask() { taskSimpleScheduler = new TaskSimpleScheduler(); autoResetEvent.Reset(); taskSimpleScheduler.StartNewTask("翻车业务逻辑", () => { // 获取待处理的车号识别记录 - 入厂方向 CmcsTrainCarriagePass inTrainCarriagePass = carriageRecognitionerDAO.GetUnHandleTrainCarriagePass(this.carriageRecognitionerMachineCode, eTrainPassDirection.进厂); if (inTrainCarriagePass != null) { this.CurrentTrainCarriagePass = inTrainCarriagePass; // 检测采样机系统的状态 string samplerSystemStatue = commonDAO.GetSignalDataValue(this.trainBeltSampler.EquipmentCode, eSignalDataName.系统.ToString()); if (samplerSystemStatue == eEquInfSamplerSystemStatus.发生故障.ToString() || samplerSystemStatue == eEquInfSamplerSystemStatus.正在卸样.ToString()) { MessageBoxEx2Show("禁止翻车, " + this.trainBeltSampler.EquipmentName + "发生故障或正在卸样,已暂停运行", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); btnStartTurnover.Enabled = true; // 取消任务 this.taskSimpleScheduler.Cancal(); return; } StartTippingTask(this.CurrentTrainCarriagePass); autoResetEvent.WaitOne(); } }, 4000); }
public object SendEvent(int events, object param) { if (threadid == MT.Thread.CurrentThread.ManagedThreadId) { bool success = true; while (success) { DoEvent(ref success); } return(OnProc(events, param)); } else { using (MT.AutoResetEvent signal = new MT.AutoResetEvent(false)) { object result = null; PostEvent(events, param, (response) => { result = response; signal.Set(); }); while (!signal.WaitOne(1)) { ; } return(result); } } }
void SchedulerThread() { int nextWait = ST.Timeout.Infinite; while (true) { newTask.WaitOne(nextWait); lock (tasks) { DateTime now = DateTime.Now; int n; for (n = 0; n < tasks.Count && tasks[n].DueTime <= now; n++) { tasks[n].Start(); tasks.RemoveAt(n); n--; } if (n < tasks.Count) { nextWait = (int)Math.Ceiling((tasks[n].DueTime - DateTime.Now).TotalMilliseconds); } else { nextWait = ST.Timeout.Infinite; } } } }
void m_VM_OnDebugCallback(DebugHookType type, string sourceName, string funcName, int line) { //FIXME: Only checking ActiveDocument since we only compile/run that single file for nows. SqDocument activeDocument = null; Dispatcher.BeginInvoke( (ThreadStart) delegate { activeDocument = ActiveDocument; }, System.Windows.Threading.DispatcherPriority.Send).Wait(); if (activeDocument != null && activeDocument.DocumentFileName == sourceName) { if (activeDocument.HandleBreakPoint(type, funcName, line)) { Dispatcher.BeginInvoke( (ThreadStart) delegate { OnScriptThreadPause(); }, System.Windows.Threading.DispatcherPriority.Send).Wait(); m_BreakPointLock.WaitOne(); } } }
void SendLongMsgFrags() { lmRestSize = lmDataBytes.Length; int count = 0; int basePosition = 0; while (lmRestSize > 0) { ackWaiting.WaitOne(); int bufSize = lmBlockSize; if (lmRestSize < lmBlockSize) { bufSize = lmLastSize; } var dataBytes = new byte[bufSize + 4 + lmMsgId.Length]; dataBytes[0] = 0xff; dataBytes[1] = 0xfe; dataBytes[2] = (byte)(count >> 8); dataBytes[3] = (byte)(count & 0xff); int baseIndex = 4; Array.Copy(lmMsgId, 0, dataBytes, baseIndex, lmMsgId.Length); baseIndex += lmMsgId.Length; Array.Copy(lmDataBytes, basePosition, dataBytes, baseIndex, bufSize); mySocket.SendTo(dataBytes, dataBytes.Length, SocketFlags.None, multicastEP); lmRestSize -= bufSize; basePosition += bufSize; count++; } }
private static void ThreadCaller() { DataQuery t = null; while (bRun) { try { if (Query.Count <= 0) { AEvent.WaitOne(); } //取出数据 lock (Query) { t = Query.Dequeue(); } if (t != null) { t.wCall(t.obj); t = null; } } catch { //LogInfo.Log.WriteInfo(ee.ToString()); } } }
public static void Main(string[] args) { var timeout = Int32.Parse(args[0]); var waitEvent = new System.Threading.AutoResetEvent(false); var hr = new HandlerRoutine(type => { Console.WriteLine($"ConsoleCtrlHandler got signal: {type}"); Console.WriteLine("Waiting for shutdown."); for (int countdown = 1; countdown <= timeout; countdown++) { Console.WriteLine($"{countdown}"); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1)); } Console.WriteLine("Done waiting - setting event and exiting."); waitEvent.Set(); return(false); }); SetConsoleCtrlHandler(hr, true); Console.WriteLine("Shutdown will wait {0} seconds.", timeout); Console.WriteLine("Waiting on handler to trigger"); waitEvent.WaitOne(); GC.KeepAlive(hr); }
FacetedMesh MeshPrim(Primitive prim) { FacetedMesh mesh = null; if (prim.Sculpt == null || prim.Sculpt.SculptTexture == UUID.Zero) { mesh = Mesher.GenerateFacetedMesh(prim, DetailLevel.Highest); } else if (prim.Sculpt.Type != SculptType.Mesh) { Image img = null; if (LoadTexture(prim.Sculpt.SculptTexture, ref img, true)) { mesh = Mesher.GenerateFacetedSculptMesh(prim, (Bitmap)img, DetailLevel.Highest); } } else { var gotMesh = new System.Threading.AutoResetEvent(false); Client.Assets.RequestMesh(prim.Sculpt.SculptTexture, (success, meshAsset) => { if (!success || !FacetedMesh.TryDecodeFromAsset(prim, meshAsset, DetailLevel.Highest, out mesh)) { Logger.Log("Failed to fetch or decode the mesh asset", Helpers.LogLevel.Warning, Client); } gotMesh.Set(); }); gotMesh.WaitOne(20 * 1000, false); } return(mesh); }
internal void NextMove() { if (IsHuman) { _wait.WaitOne(); _nextMove.PlaceHuman(); } else { Cell nextMove = null; if (Easy) { nextMove = GetRandomNextMove(); } else if (Medium) { nextMove = _random.Next(0, 2) == 0 ? GetRandomNextMove() : GetOptimalNextMove(_board.Clone(), false); } else { nextMove = GetOptimalNextMove(_board.Clone(), false); } (from cell in _board.CellsList where cell.Row == nextMove.Row && cell.Column == nextMove.Column select cell).Single().PlaceAI(); } }
/// <summary> /// Loop here to begin processing of new requests. /// </summary> /// <param name="state">Thread object state</param> private void Listen(object state) { while (listener.IsListening) { listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener); listenForNextRequest.WaitOne(); } }
public void OnBreak(object sender, EventArgs e) { CurrentBreakpoint = (Jint.Debugger.DebugInformation)e; String moduleName = breakPointsMap[CurrentBreakpoint.Module.ToLower()]; SendCommand(remoteHost, String.Format("suspended?breakpoint={0}:{1}", moduleName, CurrentBreakpoint.CurrentStatement.Source.Start.Line.ToString())); resumeEvent.WaitOne(); }
public Pipe(Socket client, ApplicationEntity scp, ApplicationEntity scu, Assembly assembly, bool log) { this.client = client; this.scp = scp; this.assembly = assembly; this.log = log; try { // connect to the SCP server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server.Blocking = true; server.Connect(new IPEndPoint(scp.Address, scp.Port)); // get the SCP thread up and running scpthread = new Thread(PipeThread); scpthread.Name = "Pipe.Scp.PipeThread"; scpthread.Start(new Connection(scp.Title, server, client, log)); if (!threadEvent.WaitOne(timeout, false)) { string message = "Pipe.Scp.Thread not started."; Logging.Log(message); throw new Exception(message); } threadEvent.Reset(); // get the SCU thread up and running scuthread = new Thread(PipeThread); scuthread.Name = "Pipe.Scu.PipeThread"; scuthread.Start(new Connection(scu.Title, client, server, log)); if (!threadEvent.WaitOne(timeout, false)) { string message = "Pipe.Scu.Thread not started."; Logging.Log(message); throw new Exception(message); } } catch { client = server = null; throw; } }
/// <summary> /// Establish an association between two Dicom devices. /// </summary> /// <param name="scp">The called device.</param> /// <param name="scu">The calling device.</param> /// <returns></returns> public bool Open(ApplicationEntity scp, ApplicationEntity scu) { this.scp = scp; this.scu = scu; // connect if (!Connect(scp.Address, scp.Port)) { return(false); } machineThread = new Thread(new ThreadStart(StateMachine)); machineThread.Name = "Association.StateMachine"; machineThread.Start(); if (!threadEvent.WaitOne(timeout, false)) { Logging.Log("Background thread not started."); State = State.Closed; return(false); } // get request AssociateRequestPdu pdu = GetAssociationRequestPdu(); // write pdu MemoryStream memory = new MemoryStream(); pdu.Write(memory); //pdu.Dump(); Dump(">> " + "A-ASSOCIATE-RQ", memory.ToArray()); State = State.Opening; NetworkStream output = new NetworkStream(socket, FileAccess.Write, false); output.Write(memory.ToArray(), 0, (int)memory.Length); if (!completeEvent.WaitOne(timeout, false)) { Logging.Log("A-ASSOCIATE-RQ FAILED"); State = State.Closed; return(false); } return(State == State.Open); }
public void Foo(Action printFoo) { for (int i = 0; i < n; i++) { slim1.WaitOne(); // printFoo() outputs "foo". Do not change or remove this line. printFoo(); slim2.Set(); } }
public void Bar(Action printBar) { for (int i = 0; i < n; i++) { slim2.WaitOne(); // printBar() outputs "bar". Do not change or remove this line. printBar(); slim1.Set(); } }
private void InstallApplication(Uri app) { var manager = new InPlaceHostingManager(app, false); manager.GetManifestCompleted += new EventHandler<GetManifestCompletedEventArgs>( OnGetManifestCompleted ); // I would love to just "await manager.GetManifestAsync" here // but GetManifestAsync returns void _event = new AutoResetEvent(false); // Console.WriteLine("Getting manifest for {0}", app); manager.GetManifestAsync(); _event.WaitOne(); // this call is synchronous // Console.WriteLine("Asserting application requirements for {0}", app); manager.AssertApplicationRequirements(true); // Console.WriteLine("AssertApplicationRequirements passes"); manager.DownloadApplicationCompleted += new EventHandler<DownloadApplicationCompletedEventArgs>( OnDownloadApplicationCompleted ); // Console.WriteLine("Downloading and installing {0}", app); manager.DownloadApplicationAsync(); _event.WaitOne(); }