public static Assembly compile(this string pathToFileToCompile, bool generateDebugSymbols) { PublicDI.CurrentScript = pathToFileToCompile; var csharpCompiler = new CSharp_FastCompiler(); csharpCompiler.generateDebugSymbols= generateDebugSymbols; var compileProcess = new System.Threading.AutoResetEvent(false); csharpCompiler.compileSourceCode(pathToFileToCompile.contents()); csharpCompiler.onCompileFail = () => compileProcess.Set(); csharpCompiler.onCompileOK = () => compileProcess.Set(); compileProcess.WaitOne(); return csharpCompiler.assembly(); }
public static Assembly compile_CodeSnippet(this string codeSnipptet, bool generateDebugSymbols) { //Note we can't use the precompiled engines here since there is an issue of the resolution of this code dependencies var csharpCompiler = new CSharp_FastCompiler(); csharpCompiler.generateDebugSymbols= generateDebugSymbols; var compileProcess = new System.Threading.AutoResetEvent(false); //csharpCompiler.compileSourceCode(pathToFileToCompile.contents()); csharpCompiler.compileSnippet(codeSnipptet); csharpCompiler.onCompileFail = () => compileProcess.Set(); csharpCompiler.onCompileOK = () => compileProcess.Set(); compileProcess.WaitOne(); var assembly = csharpCompiler.assembly(); return assembly; }
public void Should_be_able_to_configure_EasyNetQ_to_allow_message_with_a_blank_type_field() { var are = new System.Threading.AutoResetEvent(false); var validation = new NullMessageValidator(); var bus = RabbitHutch.CreateBus("host=localhost", r => r.Register<IMessageValidationStrategy>(x => validation)); bus.Subscribe<MyMessage>("null_validation_test", message => { Console.Out.WriteLine("Got message: {0}", message.Text); are.Set(); }); // now use the basic client API to publish some JSON to the message type exchange ... var factory = new RabbitMQ.Client.ConnectionFactory { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { const string exchange = "EasyNetQ_Tests_MyMessage:EasyNetQ_Tests"; const string routingKey = "#"; const string bodyString = "{ Text: \"Hello from Mr Raw :)\" }"; var body = System.Text.Encoding.UTF8.GetBytes(bodyString); var properties = channel.CreateBasicProperties(); channel.BasicPublish(exchange, routingKey, properties, body); } are.WaitOne(1000); }
public void Test() { System.Threading.AutoResetEvent evt = new System.Threading.AutoResetEvent(false); Packets.LicensePlatePacket p = null; int count = 0; Manager mnger = new Manager(new PacketSplitter()); var parser = new Parsers.LicensePlateParser(); parser.Handler += licensePlate => { System.Diagnostics.Debug.WriteLine(licensePlate.LicensePlate.LicenseNumber); p = licensePlate; ++count; if (count > 1000) { evt.Set(); } }; mnger.Parsers.Add(parser); mnger.Start(); evt.WaitOne(10000); mnger.Stop(); Assert.IsNotNull(p); }
/// </summary> /// <param name="rect"></param> internal void flushGraphics(Rectangle rect) { using (System.Threading.AutoResetEvent are = new System.Threading.AutoResetEvent(false)) { SilverlightImplementation.dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { IList<AsyncOp> tmp = renderingOperations; renderingOperations = pendingRenderingOperations; pendingRenderingOperations = tmp; if (rect == null) { _screen.Invalidate(); } else { _graphics.clip = rect; _graphics.destination.setClip(rect); _screen.Invalidate(); } _graphics.destination.setAlpha(255); _graphics.destination.setColor(0); are.Set(); }).AsTask().GetAwaiter().GetResult(); are.WaitOne(); } }
public static void Run(string[] args) { if (args.Length == 0) { Command.Application application = new Command.Application(); IDisposable telnet = Parser.Listen(application, "telnet://:23"); IDisposable tcp = Parser.Listen(application, "tcp://:20"); IDisposable console = Parser.Listen(application, "console:///"); } else { Application application = new Application(); Settings.Module settings = new Settings.Module() { //Header = "<link href=\"resources/settings.css\" rel=\"stylesheet\" type=\"text/css\"/>\n <link href=\"resources/settings.css\" rel=\"stylesheet\" type=\"text/css\"/>", }; settings.Load("loader", new Loader(settings)); settings.Load("old.object", new Object()); settings.Load("application", new Command.Application()); application.Load(settings); application.Start(); System.Threading.AutoResetEvent wait = new System.Threading.AutoResetEvent(false); application.OnClosed += () => wait.Set(); wait.WaitOne(); //application.Execute(); } }
public bool CapsQueueRunning() { if (Client.Network.CurrentSim.Caps.IsEventQueueRunning) return true; bool Success = false; // make sure caps event queue is running System.Threading.AutoResetEvent waitforCAPS = new System.Threading.AutoResetEvent(false); EventHandler<EventQueueRunningEventArgs> capsRunning = delegate(object sender, EventQueueRunningEventArgs e) { waitforCAPS.Set(); }; Client.Network.EventQueueRunning += capsRunning; if (waitforCAPS.WaitOne(10000, false)) { Success = true; } else { Success = false; Assert.Fail("Timeout waiting for event Queue to startup"); } Client.Network.EventQueueRunning -= capsRunning; return Success; }
static void Avatars_OnAvatarNames(System.Collections.Generic.Dictionary <LLUUID, string> names) { foreach (string name in names.Values) { Console.WriteLine("Name: " + name); } NameEvent.Set(); }
// Called in timer thread private void AnyPendingSignal() { if (_waiting) { _isSleeping = _sleepRequested; _waiting = false; _event.Set(); } }
public static Assembly compile_CodeSnippet(this string codeSnipptet, bool generateDebugSymbols) { //Note we can't use the precompiled engines here since there is an issue of the resolution of this code dependencies var csharpCompiler = new CSharp_FastCompiler(); csharpCompiler.generateDebugSymbols = generateDebugSymbols; var compileProcess = new System.Threading.AutoResetEvent(false); //csharpCompiler.compileSourceCode(pathToFileToCompile.contents()); csharpCompiler.compileSnippet(codeSnipptet); csharpCompiler.onCompileFail = () => compileProcess.Set(); csharpCompiler.onCompileOK = () => compileProcess.Set(); compileProcess.WaitOne(); var assembly = csharpCompiler.assembly(); return(assembly); }
/// <summary> /// Callback on change debugee state. /// </summary> /// <param name="Flags"></param> /// <param name="Argument"></param> /// <returns></returns> public void ChangeDebuggeeState(uint Flags, ulong Argument) { uint executionStatus = ((IDebugControl7)client).GetExecutionStatus(); if (executionStatus == (uint)Defines.DebugStatusGo) { debugStatusGoEvent.Set(); } }
/// <summary> /// Restart plex, wait for the specified delay between stop and start /// </summary> /// <param name="msDelay">The amount of time in ms to wait before starting after stop</param> internal void Restart(int delay) { Stop(); State = PlexState.Pending; System.Threading.AutoResetEvent autoEvent = new System.Threading.AutoResetEvent(false); System.Threading.Timer t = new System.Threading.Timer((x) => { Start(); autoEvent.Set(); }, null, delay, System.Threading.Timeout.Infinite); autoEvent.WaitOne(); t.Dispose(); }
/// <summary> /// Defines the entry point of the application. /// </summary> /// <param name="args">The arguments.</param> public static void Main(string[] args) { if (args[0] != null) { logFile = args[0]; } else { System.Console.WriteLine("Missing Argument (logfile)"); } // Main processing Thread System.Threading.Thread handler = new System.Threading.Thread(new System.Threading.ThreadStart(HandleMessage)) { IsBackground = true }; handler.Start(); /* Main Loop */ /* Listen for incoming data on udp port 514 (default for SysLog events) */ while (queueing || messageQueue.Count != 0) { try { anyIP.Port = 514; // https://www.real-world-systems.com/docs/logger.1.html // sudo apt-get install bsdutils // logger -p auth.notice "Some message for the auth.log file" // logger -p auth.notice "Some message for the auth.log file" --server 127.0.0.1 // Receive the message byte[] bytesReceive = udpListener.Receive(ref anyIP); // push the message to the queue, and trigger the queue Data.Message msg = new Data.Message { MessageText = System.Text.Encoding.ASCII.GetString(bytesReceive), RecvTime = System.DateTime.Now, SourceIP = anyIP.Address }; lock (messageQueue) { messageQueue.Enqueue(msg); } messageTrigger.Set(); } catch (System.Exception ex) { // ToDo: Add Error Handling System.Console.WriteLine(ex.Message); } } }
public IEnumerable <Toot> Load(bool hasFederated, int take = int.MaxValue) { var accessors = new List <ITootAccessor> { new TootLocal() }; if (hasFederated) { accessors.AddRange(_federates.Select(f => new TootRemote(f) as ITootAccessor)); } #if NET35 var sync = new object(); var toots = new List <Toot>(); var counter = accessors.Count; var wait = new System.Threading.AutoResetEvent(false); foreach (var accessor in accessors) { System.Threading.ThreadPool.QueueUserWorkItem(acs => { var loaded = (acs as ITootAccessor).Load(take); System.Threading.Interlocked.Decrement(ref counter); lock (sync) { if (loaded != null) { toots.AddRange(loaded); } } if (counter <= 0) { wait.Set(); } }, accessor); } wait.WaitOne(); #else var toots = new System.Collections.Concurrent.ConcurrentBag <Toot>(); var tasks = accessors.Select(acs => System.Threading.Tasks.Task.Factory.StartNew(() => { var loaded = (acs as ITootAccessor).Load(take); if (loaded != null) { foreach (var t in loaded) { toots.Add(t); } } })); System.Threading.Tasks.Task.WaitAll(tasks.ToArray()); #endif return(toots.OrderByDescending(t => t.CreateAt).ThenBy(t => t.IsRemote)); }
// Sync up with the GLib thread. Should be called after the // name, role, or parent are changed in UiaAtkBridge when // checking for events, since we defer to an idle // handler to call atk to avoid deadlock when atk // emits signals. Called by RunInGuiThread in // UiaAtkBridge. public static void GlibSync() { System.Threading.AutoResetEvent sync = new System.Threading.AutoResetEvent(false); GLib.Timeout.Add(0, new GLib.TimeoutHandler(delegate { sync.Set(); return(false); })); sync.WaitOne(); sync.Close(); }
public void GivenIHaveAServer() { var wait = new System.Threading.AutoResetEvent(false); var server = ScenarioContext.Current.Get<System.ServiceModel.ServiceHost>(); server.Opened += (sender, args) => wait.Set(); server.Open(); Assert.IsTrue(wait.WaitOne(TimeSpan.FromSeconds(1))); }
public void GivenIHaveAServer() { var wait = new System.Threading.AutoResetEvent(false); var server = ScenarioContext.Current.Get <System.ServiceModel.ServiceHost>(); server.Opened += (sender, args) => wait.Set(); server.Open(); Assert.IsTrue(wait.WaitOne(TimeSpan.FromSeconds(1))); }
// Sync up with the GLib thread. Should be called after the // name, role, or parent are changed in UiaAtkBridge when // checking for events, since we defer to an idle // handler to call atk to avoid deadlock when atk // emits signals. Called by RunInGuiThread in // UiaAtkBridge. public static void GlibSync () { System.Threading.AutoResetEvent sync = new System.Threading.AutoResetEvent (false); GLib.Timeout.Add (0, new GLib.TimeoutHandler (delegate { sync.Set (); return false; })); sync.WaitOne (); sync.Close (); }
public void Stop() { if (waitfordatathread != null) { stophandle.Set(); waitfordatathread.Join(); waitfordatathread = null; System.Diagnostics.Debug.WriteLine("IDL Stop"); } }
public void WorkflowIdled(Object sender, WorkflowEventArgs eventArgs) { if (eventArgs.WorkflowInstance.InstanceId != workflowInstance.InstanceId) { return; } SetWorkflowStatus(WorkflowStatus.Idled); if (workflowResponse.UserInteractionRequest.UserInteractionType != UserInteractionType.NotSpecified) { if (waitHandle != null) { waitHandle.Set(); } } return; }
public static void Add(string s) { if (s != null && s.Length != 0) { var hash = s.GetHashCode(); access.WaitOne(); Table [hash] = s; access.Set(); } }
/// <summary> /// The timer event for the time out. If this triggers, we assume /// the port is filtered. /// </summary> /// <param name="source"> /// Source. /// </param> /// <param name="e"> /// Event args. /// </param> private void TimeOut(object source, ElapsedEventArgs e) { m_timeoutTimer.Enabled = false; if (!m_working) { return; } if (PortReply != null) { PortReply(m_remoteEndPoint, TcpPortState.Filtered); } // increment the port m_portIndex++; // check to see if the port scan is complete if (m_portIndex == m_ports.Length) { if (ScanComplete != null) { ScanComplete(); } m_sendTimer = null; m_working = false; m_waitObject.Set(); return; } // check the next port if (m_sendTimer == null) { SendRequest(); } else { m_sendTimer.Enabled = true; } }
private string GetObjectName(Primitive prim, int distance) { string name = "Loading..."; string ownerName = "Loading..."; if (prim.Properties != null) { name = prim.Properties.Name; // prim.Properties.GroupID is the actual group when group owned, not prim.GroupID if (UUID.Zero == prim.Properties.OwnerID && PrimFlags.ObjectGroupOwned == (prim.Flags & PrimFlags.ObjectGroupOwned) && UUID.Zero != prim.Properties.GroupID) { System.Threading.AutoResetEvent nameReceivedSignal = new System.Threading.AutoResetEvent(false); EventHandler <GroupNamesEventArgs> cbGroupName = new EventHandler <GroupNamesEventArgs>( delegate(object sender, GroupNamesEventArgs e) { if (e.GroupNames.ContainsKey(prim.Properties.GroupID)) { e.GroupNames.TryGetValue(prim.Properties.GroupID, out ownerName); if (string.IsNullOrEmpty(ownerName)) { ownerName = "Loading..."; } if (null != nameReceivedSignal) { nameReceivedSignal.Set(); } } }); client.Groups.GroupNamesReply += cbGroupName; client.Groups.RequestGroupName(prim.Properties.GroupID); nameReceivedSignal.WaitOne(5000, false); nameReceivedSignal.Close(); client.Groups.GroupNamesReply -= cbGroupName; } else { ownerName = instance.Names.Get(prim.Properties.OwnerID); } } if (prim.ParentID == client.Self.LocalID) { return(string.Format("{0} attached to {1}", name, prim.PrimData.AttachmentPoint.ToString())); } else if (ownerName != "Loading...") { return(String.Format("{0} ({1}m) owned by {2}", name, distance, ownerName)); } else { return(String.Format("{0} ({1}m)", name, distance)); } }
/// <summary> /// Exectute the command /// </summary> /// <param name="args"></param> /// <param name="fromAgentID"></param> /// <returns></returns> public override string Execute(string[] args, UUID fromAgentID) { if (args.Length < 1) { return("Usage: viewnote [notecard asset uuid]"); } UUID note; if (!UUID.TryParse(args[0], out note)) { return("First argument expected agent UUID."); } System.Threading.AutoResetEvent waitEvent = new System.Threading.AutoResetEvent(false); System.Text.StringBuilder result = new System.Text.StringBuilder(); // define a delegate to handle the reply AssetManager.AssetReceivedCallback del = delegate(AssetDownload transfer, Asset asset) { if (transfer.Success) { result.AppendFormat("Raw Notecard Data: " + System.Environment.NewLine + " {0}", Utils.BytesToString(asset.AssetData)); waitEvent.Set(); } }; // verify asset is loaded in store if (Client.Inventory.Store.Contains(note)) { // retrieve asset from store InventoryItem ii = (InventoryItem)Client.Inventory.Store[note]; // subscribe to reply event Client.Assets.OnAssetReceived += del; // make request for asset Client.Assets.RequestInventoryAsset(ii, true); // wait for reply or timeout if (!waitEvent.WaitOne(10000, false)) { result.Append("Timeout waiting for notecard to download."); } // unsubscribe from reply event Client.Assets.OnAssetReceived -= del; } else { result.Append("Cannot find asset in inventory store, use 'i' to populate store"); } // return results return(result.ToString()); }
public static Texture GetByUUID(Guid id, Color?defaultColor) { if (_memoryCache.TryGetValue(id, out var cachedTexture)) { return(cachedTexture); } if (_assetReader == null && defaultColor == null) { return(DEFAULT); // No cache needed for default. } Texture texture = null; Exception ex = null; var wait = new System.Threading.AutoResetEvent(false); _assetReader.GetAssetAsync(id, asset => { if (asset == null || !(asset?.IsTextureAsset() ?? false)) { texture = new Texture(color: defaultColor); // No cache when the asset was not found: maybe next time it will be. } else { try { texture = new Texture(asset); _memoryCache.TryAdd(id, texture); } catch (Exception e) { ex = e; } } wait.Set(); }); wait.WaitOne(60000); if (ex != null) { throw new Exception("See inner exception", ex); } if (texture == null && defaultColor == null) { return(DEFAULT); // No cache needed for default. } else if (texture == null) { return(new Texture(color: defaultColor)); } return(texture); }
/// <summary> /// Exectute the command /// </summary> /// <param name="args"></param> /// <param name="fromAgentID"></param> /// <returns></returns> public override string Execute(string[] args, UUID fromAgentID) { if (args.Length < 1) { return "Usage: viewnote [notecard asset uuid]"; } UUID note; if (!UUID.TryParse(args[0], out note)) { return "First argument expected agent UUID."; } System.Threading.AutoResetEvent waitEvent = new System.Threading.AutoResetEvent(false); System.Text.StringBuilder result = new System.Text.StringBuilder(); // define a delegate to handle the reply AssetManager.AssetReceivedCallback del = delegate(AssetDownload transfer, Asset asset) { if (transfer.Success) { result.AppendFormat("Raw Notecard Data: " + System.Environment.NewLine + " {0}", Utils.BytesToString(asset.AssetData)); waitEvent.Set(); } }; // verify asset is loaded in store if (Client.Inventory.Store.Contains(note)) { // retrieve asset from store InventoryItem ii = (InventoryItem)Client.Inventory.Store[note]; // subscribe to reply event Client.Assets.OnAssetReceived += del; // make request for asset Client.Assets.RequestInventoryAsset(ii, true); // wait for reply or timeout if (!waitEvent.WaitOne(10000, false)) { result.Append("Timeout waiting for notecard to download."); } // unsubscribe from reply event Client.Assets.OnAssetReceived -= del; } else { result.Append("Cannot find asset in inventory store, use 'i' to populate store"); } // return results return result.ToString(); }
public void Stop() { if (m_timer != null && m_thread != null) { m_timer.Set(); if (m_thread.ManagedThreadId != System.Threading.Thread.CurrentThread.ManagedThreadId) { m_thread.Join(); } } }
public static System.Tuple <Boolean, int, String[]> runExe(String cmd, String args, int timeout = 60) { System.Tuple <Boolean, int, String[]> ret = new System.Tuple <Boolean, int, String[]>(false, -1, null); logIt(String.Format("runExe: ++ cmd={0} args={1}", cmd, args)); try { int exit_code = -1; System.Threading.AutoResetEvent ev = new System.Threading.AutoResetEvent(false); List <String> lines = new List <String>(); System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.FileName = cmd; p.StartInfo.Arguments = args; p.StartInfo.UseShellExecute = false; p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.OutputDataReceived += (obj, e) => { if (!String.IsNullOrEmpty(e.Data)) { logIt(e.Data); lines.Add(e.Data); } if (e.Data == null) { // pipe closed ev.Set(); } }; p.Start(); p.BeginOutputReadLine(); if (p.WaitForExit(timeout)) { exit_code = p.ExitCode; ev.WaitOne(2500); } else { if (!p.HasExited) { p.Kill(); } exit_code = 1460; } ret = new System.Tuple <Boolean, int, String[]>(true, exit_code, lines.ToArray()); } catch (System.Exception ex) { logIt(ex.Message); logIt(ex.StackTrace); } logIt(String.Format("runExe: -- ret={0} code={1}", ret.Item1, ret.Item2)); return(ret); }
public void Reading_the_status_of_a_non_default_build() { // Given CreateClient(); var expectedBuildInfo = new Build() { Status = "SUCCESS" }; string expectedBuildConfigurationId = "BuildServer_Branch"; var locator = BuildLocator.WithDimensions( buildType: BuildTypeLocator.WithId(expectedBuildConfigurationId), maxResults: 1, branch: "branched:true"); var mockBuilds = ExpectReadOfBuildStatus(expectedBuildConfigurationId, expectedBuildInfo, locator: locator); ExpectReadOfBuildConfiguration(expectedBuildConfigurationId, expectedBuildConfigurationId + "_hello"); var server = new TeamCityServer("localhost", "Username", "Password"); var wait = new System.Threading.AutoResetEvent(false); BuildStatus?actualStatus = null; string actualBuildConfigurationId = null; System.Threading.Thread actualThread = null; string actualName = null; server.ReadBuildStatusComplete += (sender, e) => { actualThread = System.Threading.Thread.CurrentThread; actualStatus = e.Status; actualBuildConfigurationId = e.BuildConfigurationId; actualName = e.Name; wait.Set(); }; server.UseDefault = false; // Set the server to not use the builds default branch // When server.ReadBuildStatusAsync(expectedBuildConfigurationId); Assert.IsTrue(wait.WaitOne(5000)); // Then clientMock.VerifyAll(); mockBuilds.VerifyAll(); Assert.AreEqual(BuildStatus.Success, actualStatus); Assert.AreEqual(expectedBuildConfigurationId, actualBuildConfigurationId); Assert.AreEqual(expectedBuildConfigurationId + "_hello", actualName); Assert.AreNotEqual(System.Threading.Thread.CurrentThread, actualThread); }
/// <summary> /// 转换成Task异步 /// </summary> /// <typeparam name="U">返回类型</typeparam> /// <param name="q"></param> /// <returns></returns> public static Task <U> ResultAsync <U>(this InvokeOperation <U> q) { return(Task.Run(() => { System.Threading.AutoResetEvent auto = new System.Threading.AutoResetEvent(false); q.Completed += (a, b) => auto.Set(); auto.WaitOne(); auto.Dispose(); return q.Value; })); }
private void WebSocketClient_OnQueueMessage(IQueueMessage message, QueueMessageEventArgs e) { if (correlationId == message.correlationId && message.data != null) { command = Newtonsoft.Json.JsonConvert.DeserializeObject <Interfaces.mq.RobotCommand>(message.data.ToString()); if (command.command == "invokefailed" || command.command == "invokeaborted" || command.command == "invokecompleted") { workItemsWaiting.Set(); } } }
/// <summary> /// Process the search reply /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Directory_DirLand(object sender, DirLandReplyEventArgs e) { foreach (DirectoryManager.DirectoryParcel searchResult in e.DirParcels) { // add the results to the StringBuilder object that contains the results result.AppendLine(searchResult.ToString()); } result.AppendFormat("{0} results" + System.Environment.NewLine, e.DirParcels.Count); // let the calling method know we have data waitQuery.Set(); }
public static void PrintUpdateInfo() { try { // ProgramLog.Log ("Attempting to retreive Build Info..."); var buildInfo = String.Empty; using (var ctx = new WebClient()) { using (var prog = new ProgressLogger(100, "Downloading build information...")) { var signal = new System.Threading.AutoResetEvent(false); ctx.DownloadProgressChanged += (sender, args) => { prog.Value = args.ProgressPercentage; }; ctx.DownloadStringCompleted += (sender, args) => { var arg = args as DownloadStringCompletedEventArgs; buildInfo = arg.Result; signal.Set(); }; ctx.DownloadStringAsync(new Uri(UpdateInfo)); signal.WaitOne(); } } if (String.IsNullOrEmpty(buildInfo)) { ProgramLog.Log("Failed to download build information."); return; } var toString = "comments: "; //if (buildInfo.ToLower().Contains(toString)) var index = buildInfo.ToLower().IndexOf(toString); if (index != -1) { buildInfo = buildInfo.Remove(0, index + toString.Length).Trim(); foreach (var pair in BuildInfoReplacements) { buildInfo = buildInfo.Replace(pair.Key, pair.Value); } ProgramLog.Log("Build Comments: \n\t " + buildInfo); } } catch (Exception) { } }
public void workerB() { System.Threading.Thread.Sleep(5000); gemeinsam = 100; Debug.Write("B, vor der 1. Semaphore. gemeinsam = " + gemeinsam); // Signalisieren A, das ich bereit bin signal.Set(); Debug.WriteLine("B, nach dem freigegeben. gemeinsam = " + gemeinsam); }
private void ProcessJob() { Task task = null; lock (tasks) { if (tasks.Count != 0) { LinkedListNode <Task> node = tasks.First; tasks.Remove(node); task = node.Value; node.Value = null; stock.AddLast(node); } if (tasks.Count != 0) { jobEvent.Set(); } } if ((task != null) && !exit) { try { task.state = TaskState.Running; task.job.Invoke(); task.SetResult(TaskState.RanToCompletion); } catch (System.Exception ec) { task.exception = ec; task.SetResult(TaskState.Faulted); if (ec is System.Threading.ThreadAbortException) { } else { UnityEngine.Debug.LogException(ec); } } } }
internal void _AddReceivedMessage(NetworkIncommingMessage _Message) { if (_Message.MessageType == NetworkMessageType.RawData) { m_Messages.Enqueue(_Message); m_NewMessageEvent.Set(); } else { m_InternalMessages.Enqueue(_Message); } }
/// <summary> /// Enqueues a batch. /// </summary> /// <param name="desc">the descriptor of the batch. If the batch is rejected because another batch in the queue already has the same id, the Id member is set to 0.</param> /// <returns>true if the batch has been accepted, false otherwise.</returns> public bool Enqueue(DataProcessingBatchDesc desc) { if (m_IsWillingToProcess[0] == false) { return(false); } SySal.OperaDb.OperaDbConnection conn = null; try { conn = new SySal.OperaDb.OperaDbConnection(OperaDataProcessingServer.DBServer, OperaDataProcessingServer.DBUserName, OperaDataProcessingServer.DBPassword); conn.Open(); SySal.OperaDb.ComputingInfrastructure.UserPermission [] rights = new SySal.OperaDb.ComputingInfrastructure.UserPermission[1]; rights[0].DB_Site_Id = OperaDataProcessingServer.IdSite; rights[0].Designator = SySal.OperaDb.ComputingInfrastructure.UserPermissionDesignator.ProcessData; rights[0].Value = SySal.OperaDb.ComputingInfrastructure.UserPermissionTriState.Grant; if (desc.Token != null) { if (!SySal.OperaDb.ComputingInfrastructure.User.CheckTokenAccess(desc.Token, rights, conn, null)) { throw new Exception("The user does not own the permission to process data in this site"); } } else { SySal.OperaDb.ComputingInfrastructure.User.CheckAccess(SySal.OperaDb.ComputingInfrastructure.User.CheckLogin(desc.Username, desc.Password, conn, null), rights, true, conn, null); } conn.Close(); conn = null; } catch (System.Exception) { if (conn != null) { conn.Close(); } return(false); } lock (m_Queue) { foreach (SySal.DAQSystem.DataProcessingBatchDesc d in m_Queue) { if (d.Id == desc.Id) { desc.Id = 0; return(false); } } desc.Finished = desc.Started = desc.Enqueued = System.DateTime.Now; m_Queue.Add(desc); m_QueueNotEmpty.Set(); } return(true); }
void Assets_UploadProgress(object sender, AssetUploadEventArgs e) { if (e.Upload.Transferred == e.Upload.Size) { WaitForUploadComplete.Set(); } else { //Console.WriteLine("Progress: {0}/{1} {2}/{3} {4}", upload.XferID, upload.ID, upload.Transferred, upload.Size, upload.Success); Console.Write("."); } }
void CloseCamera() { if (_ptGreyCamera != null) { _ptGreyCamera.Close(); } if (_ptGreyStopImageThreadEvent != null) { _ptGreyStopImageThreadEvent.Set(); } }
private void ShowCurrents(User user, string[] arguments) { if (user.Context == null) { throw new UnauthorizedCommandException(GetCurrentsCommand); } LersServer server = user.Context.Server; long chatId = user.ChatId; var measurePoint = server.GetMeasurePoints(arguments).FirstOrDefault(); if (measurePoint == null) { bot.SendText(chatId, "Точка учёта не найдена"); return; } bot.SendText(chatId, $"Точка учёта {measurePoint.FullTitle}"); var options = new MeasurePointPollCurrentOptions { StartMode = Lers.Common.PollManualStartMode.Force }; int pollSessionId = measurePoint.PollCurrent(options); bot.SendText(chatId, "Запущен опрос"); var autoResetEvent = new System.Threading.AutoResetEvent(false); MeasurePointData.CurrentsSaved += (sender, e) => { try { SendCurrents(chatId, e.Consumption); autoResetEvent.Set(); } catch (Exception exc) { bot.SendText(chatId, exc.Message); } }; MeasurePointData.SubscribeSaveCurrents(server, pollSessionId); if (!autoResetEvent.WaitOne(120000)) { bot.SendText(chatId, "Не удалось получить текущие данные за 2 минуты."); } MeasurePointData.UnsubscribeSaveCurrents(server); }
public override void Tick() { mLogicBegin.WaitOne(); mLogicBegin.Reset(); IsTicking = true; TickAwaitEvent(); CEngine.Instance.TryTickLogic(); IsTicking = false; mLogicEnd.Set(); }
public void GivenIHaveAClient(string endpoint) { var wait = new System.Threading.AutoResetEvent(false); var client = new Wcf.ServiceClient(endpoint); client.InnerChannel.Opened += (sender, args) => wait.Set(); client.Open(); Assert.IsTrue(wait.WaitOne(TimeSpan.FromSeconds(1))); ScenarioContext.Current.Set(client); }
public override string Execute(string[] args, UUID fromAgentID) { System.Threading.AutoResetEvent waitBalance = new System.Threading.AutoResetEvent(false); EventHandler<BalanceEventArgs> del = delegate(object sender, BalanceEventArgs e) { waitBalance.Set(); }; Client.Self.MoneyBalance += del; Client.Self.RequestBalance(); String result = "Timeout waiting for balance reply"; if (waitBalance.WaitOne(10000, false)) { result = Client.ToString() + " has L$: " + Client.Self.Balance; } Client.Self.MoneyBalance -= del; return result; }
public override string Execute(string[] args, Guid fromAgentID) { System.Threading.AutoResetEvent waitBalance = new System.Threading.AutoResetEvent(false); AgentManager.BalanceCallback del = delegate(int balance) { waitBalance.Set(); }; Client.Self.OnBalanceUpdated += del; Client.Self.RequestBalance(); String result = "Timeout waiting for balance reply"; if (waitBalance.WaitOne(10000, false)) { result = Client.ToString() + " has L$: " + Client.Self.Balance; } Client.Self.OnBalanceUpdated -= del; return result; }
public void TestSendMessage() { var are = new System.Threading.AutoResetEvent(false); var connection = new SignalR.Client.Hubs.HubConnection("http://localhost:8081/"); var chatHub = connection.CreateProxy("chatHub_4"); connection.Start().ContinueWith(action => { if (action.IsFaulted) { Assert.Fail(string.Format("Error starting connection: {0}.", action.Exception.ToString())); } else Console.WriteLine("Connection started."); }).Wait(); bool addMessageExecuted = false; chatHub.On<WebApplication.ChatHub_4.MessageData>("AddMessage", (data) => { Assert.AreEqual("test name", data.UserName); Assert.AreEqual("hallo test world!", data.Message); addMessageExecuted = true; are.Set(); }); chatHub.Invoke("SendMessage", new { UserName = "******", Message = "hallo test world!" }).ContinueWith(task => { if (task.IsFaulted) Assert.Fail(string.Format("'SendMessage' invoke failed: {0}.", task.Exception.ToString())); else Console.WriteLine("'SendMessage' invoke completed."); }).Wait(); are.WaitOne(TimeSpan.FromSeconds(5)); Assert.IsTrue(addMessageExecuted); }
public static string downloadFile(this Uri uri, string targetFile) { if (uri.isNull()) return null; "Downloading file {0} to location:{1}".info(uri.str(), targetFile); if (targetFile.fileExists()) // don't download if file already exists { "File already existed, so skipping download".debug(); return targetFile; } var sync = new System.Threading.AutoResetEvent(false); var downloadControl = O2Gui.open<DownloadFile>("Downloading: {0}".format(uri.str()), 455 ,170 ); downloadControl.setAutoCloseOnDownload(true); downloadControl.setCallBackWhenCompleted((file)=> downloadControl.parentForm().close()); downloadControl.onClosed(()=>sync.Set()); downloadControl.setDownloadDetails(uri.str(), targetFile); downloadControl.downloadFile(); sync.WaitOne(); // wait for download complete or form to be closed targetFile.file_WaitFor_CanOpen(); if (targetFile.fileExists()) return targetFile; return null; }
public void DeviceLocator_Notifications_SearchResponseMissingCacheHeaderIsNonCacheable() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var publishedDevice = CreateDeviceTree(); DiscoveredSsdpDevice device = null; var receivedNotification = false; using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { device = args.DiscoveredDevice; receivedNotification = true; eventSignal.Set(); }; var t = deviceLocator.SearchAsync(TimeSpan.FromSeconds(3)); System.Threading.Thread.Sleep(500); server.MockReceiveMessage(GetMockSearchResponseWithCustomCacheHeader(publishedDevice, publishedDevice.Udn, null)); eventSignal.WaitOne(10000); var results = t.GetAwaiter().GetResult(); Assert.IsNotNull(results); Assert.IsTrue(results.Any()); Assert.IsTrue(receivedNotification); Assert.IsNotNull(device); Assert.AreEqual(device.Usn, String.Format("{0}:{1}", publishedDevice.Udn, publishedDevice.FullDeviceType)); Assert.AreEqual(device.NotificationType, publishedDevice.Udn); } }
public void DeviceLocator_Notifications_HandlesByeByeDuringSearch() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); DiscoveredSsdpDevice device = null; var receivedNotification = false; using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceUnavailable += (sender, args) => { device = args.DiscoveredDevice; receivedNotification = true; eventSignal.Set(); }; deviceLocator.StartListeningForNotifications(); server.MockReceiveBroadcast(GetMockAliveNotification()); server.WaitForMessageToProcess(10000); var t = deviceLocator.SearchAsync(TimeSpan.FromSeconds(3)); System.Threading.Thread.Sleep(500); server.MockReceiveBroadcast(GetMockByeByeNotification()); eventSignal.WaitOne(10000); var results = t.GetAwaiter().GetResult(); Assert.IsNotNull(results); Assert.IsFalse(results.Any()); } Assert.IsTrue(receivedNotification); Assert.IsNotNull(device); }
private static string FetchUpdate(PackageInfo info) { var tmp = Path.Combine(Environment.CurrentDirectory, ".repo"); var di = new DirectoryInfo(tmp); if (!di.Exists) { di.Create(); di.Attributes = FileAttributes.Hidden; } var isGitHub = System.Text.RegularExpressions.Regex.IsMatch(info.DownloadUrl, "https://api.github.com/repos/.*/.*/releases", System.Text.RegularExpressions.RegexOptions.Singleline); if (isGitHub) { var release = GetGitHubRelease(info.DownloadUrl); if (release.Assets != null && release.Assets.Length > 0) { var saveAs = Path.Combine(tmp, release.Assets[0].FileName); if (File.Exists(saveAs)) File.Delete(saveAs); using (var wc = new ProgressWebClient("Downloading")) { var wait = new System.Threading.AutoResetEvent(false); wc.DownloadFileCompleted += (s, a) => { wait.Set(); }; wc.DownloadFileAsync(new Uri(release.Assets[0].DownloadUrl), saveAs); wait.WaitOne(); return saveAs; } } else throw new RepositoryError("Failed to fetch release from GitHub"); } else { var fileName = info.DownloadUrl; var last = fileName.LastIndexOf("/"); if (last > -1) { fileName = fileName.Remove(0, last); } var saveAs = Path.Combine(tmp, fileName); if (File.Exists(saveAs)) File.Delete(saveAs); using (var wc = new ProgressWebClient("Downloading")) { var wait = new System.Threading.AutoResetEvent(false); wc.DownloadFileCompleted += (s, a) => { wait.Set(); }; wc.DownloadFileAsync(new Uri(info.DownloadUrl), saveAs); wait.WaitOne(); return saveAs; } } }
public void DeviceLocator_Notifications_RaisesDeviceAvailableWithMatchedNotificationFilter() { var publishedDevice = CreateDeviceTree(); var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var discoveredDevices = new List<DiscoveredSsdpDevice>(); using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { discoveredDevices.Add(args.DiscoveredDevice); eventSignal.Set(); }; deviceLocator.NotificationFilter = "uuid: " + System.Guid.NewGuid().ToString(); deviceLocator.StartListeningForNotifications(); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice)); eventSignal.WaitOne(1000); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice.Devices.First())); eventSignal.WaitOne(1000); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice.Devices.First().Devices.First())); eventSignal.WaitOne(1000); } Assert.IsFalse(discoveredDevices.Any()); }
public bool CapsQueueRunning() { if (Client.Network.CurrentSim.Caps.IsEventQueueRunning) return true; bool Success = false; // make sure caps event queue is running System.Threading.AutoResetEvent waitforCAPS = new System.Threading.AutoResetEvent(false); NetworkManager.EventQueueRunningCallback capsRunning = delegate(Simulator sim) { waitforCAPS.Set(); }; Client.Network.OnEventQueueRunning += capsRunning; if (waitforCAPS.WaitOne(10000, false)) { Success = true; } else { Success = false; Assert.Fail("Timeout waiting for event Queue to startup"); } Client.Network.OnEventQueueRunning -= capsRunning; return Success; }
public void DeviceLocator_Notifications_DoesNotRaiseDeviceAvailableWithUnmatchedNotificationFilter() { var publishedDevice = CreateDeviceTree(); var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var discoveredDevices = new List<DiscoveredSsdpDevice>(); using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { discoveredDevices.Add(args.DiscoveredDevice); eventSignal.Set(); }; deviceLocator.NotificationFilter = publishedDevice.Devices.First().Udn; deviceLocator.StartListeningForNotifications(); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice)); eventSignal.WaitOne(1000); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice.Devices.First())); eventSignal.WaitOne(1000); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice.Devices.First().Devices.First())); eventSignal.WaitOne(1000); } Assert.IsTrue(discoveredDevices.Any()); Assert.IsFalse(discoveredDevices.Any((d) => { return !d.Usn.StartsWith(publishedDevice.Devices.First().Udn); })); }
public void DeviceLocator_Notifications_ReceivesByeByeNotificationsForUnknownDevice() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var receivedNotification = false; DiscoveredSsdpDevice device = null; bool expired = false; using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceUnavailable += (sender, args) => { device = args.DiscoveredDevice; expired = args.Expired; receivedNotification = true; eventSignal.Set(); }; deviceLocator.StartListeningForNotifications(); server.MockReceiveBroadcast(GetMockByeByeNotification()); eventSignal.WaitOne(10000); } Assert.IsTrue(receivedNotification); Assert.IsNotNull(device); Assert.IsFalse(expired); }
public void DeviceLocator_SearchAsync_RaisesDeviceAvailableOnResponse() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var publishedDevice = CreateDeviceTree(); DiscoveredSsdpDevice device = null; bool newlyDiscovered = false; var receivedNotification = false; using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { device = args.DiscoveredDevice; newlyDiscovered = args.IsNewlyDiscovered; receivedNotification = true; eventSignal.Set(); }; var task = deviceLocator.SearchAsync(TimeSpan.FromSeconds(2)); server.MockReceiveMessage(GetMockSearchResponse(publishedDevice, publishedDevice.Udn)); eventSignal.WaitOne(10000); Assert.IsTrue(receivedNotification); var results = task.GetAwaiter().GetResult(); Assert.IsNotNull(results); Assert.IsTrue(results.Any()); Assert.IsTrue(results.First().Usn == device.Usn); } }
public void DeviceLocator_SearchAsync_ReturnsCachedDevices() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); DiscoveredSsdpDevice device = null; bool newlyDiscovered = false; var receivedNotification = false; using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { device = args.DiscoveredDevice; newlyDiscovered = args.IsNewlyDiscovered; receivedNotification = true; eventSignal.Set(); }; deviceLocator.StartListeningForNotifications(); server.MockReceiveBroadcast(GetMockAliveNotification()); eventSignal.WaitOne(10000); Assert.IsTrue(receivedNotification); var results = deviceLocator.SearchAsync(TimeSpan.Zero).GetAwaiter().GetResult(); Assert.IsNotNull(results); Assert.IsTrue(results.Any()); Assert.IsTrue(results.First().Usn == device.Usn); } }
public void DeviceLocator_SearchAsync_FiltersNotificationsDuringSearch() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var publishedDevice = CreateDeviceTree(); var publishedDevice2 = CreateDeviceTree(); deviceLocator.NotificationFilter = publishedDevice.Udn; deviceLocator.StartListeningForNotifications(); DiscoveredSsdpDevice device = null; bool newlyDiscovered = false; var receivedNotification = false; using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { device = args.DiscoveredDevice; newlyDiscovered = args.IsNewlyDiscovered; receivedNotification = true; eventSignal.Set(); }; var task = deviceLocator.SearchAsync(publishedDevice.Udn); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice2)); server.WaitForMessageToProcess(5000); eventSignal.Reset(); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice)); server.WaitForMessageToProcess(5000); eventSignal.WaitOne(10000); Assert.IsTrue(receivedNotification); var results = task.GetAwaiter().GetResult(); Assert.IsNotNull(results); Assert.AreEqual(1, results.Count()); Assert.IsTrue(results.First().Usn == device.Usn); } }
public void DeviceLocator_Notifications_SubsequentNotificationsUpdatesSearchResults() { var publishedDevice = CreateDeviceTree(); var server = new MockCommsServer(); using (var deviceLocator = new MockDeviceLocator(server)) { var discoveredDevices = new List<DiscoveredSsdpDevice>(); using (var signal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { discoveredDevices.Add(args.DiscoveredDevice); signal.Set(); }; deviceLocator.StartListeningForNotifications(); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice)); signal.WaitOne(10000); var updatedDevice = CreateDeviceTree(); updatedDevice.Uuid = publishedDevice.Uuid; updatedDevice.Location = new Uri("http://somewhereelse:1701"); updatedDevice.CacheLifetime = TimeSpan.FromDays(365); server.MockReceiveBroadcast(GetMockAliveNotification(updatedDevice)); signal.WaitOne(10000); } var first = discoveredDevices.First(); var second = discoveredDevices.Last(); Assert.IsTrue(discoveredDevices.Any()); Assert.AreNotEqual(first.DescriptionLocation, second.DescriptionLocation); Assert.AreNotEqual(first.CacheLifetime, second.CacheLifetime); Assert.AreEqual(second.CacheLifetime, TimeSpan.FromDays(365)); Assert.AreEqual(second.DescriptionLocation, new Uri("http://somewhereelse:1701")); } }
public void DeviceLocator_Notifications_SubsequentNotificationsUpdatesCachedDescriptionLocation() { var publishedDevice = CreateDeviceTree(); var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var discoveredDevices = new List<DiscoveredSsdpDevice>(); using (var signal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { discoveredDevices.Add(args.DiscoveredDevice); signal.Set(); }; deviceLocator.StartListeningForNotifications(); server.MockReceiveBroadcast(GetMockAliveNotification(publishedDevice)); signal.WaitOne(10000); var t = deviceLocator.SearchAsync(TimeSpan.FromSeconds(5)); var updatedDevice = CreateDeviceTree(); updatedDevice.Uuid = publishedDevice.Uuid; updatedDevice.Location = new Uri("http://somewhereelse:1701"); server.MockReceiveBroadcast(GetMockAliveNotification(updatedDevice)); signal.WaitOne(10000); var results = t.GetAwaiter().GetResult(); Assert.IsNotNull(results); Assert.IsTrue(results.Any()); Assert.AreEqual(String.Format("{0}::{1}", publishedDevice.Udn, publishedDevice.FullDeviceType), discoveredDevices.Last().Usn); var first = discoveredDevices.First(); var second = discoveredDevices.Last(); Assert.AreNotEqual(first.DescriptionLocation, second.DescriptionLocation); Assert.AreEqual(second.DescriptionLocation, new Uri("http://somewhereelse:1701")); } }
public void DeviceLocator_Notifications_StopListeningNoLongerReceivesNotifications() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); deviceLocator.StartListeningForNotifications(); deviceLocator.StopListeningForNotifications(); var receivedNotification = false; using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { receivedNotification = true; eventSignal.Set(); }; server.MockReceiveBroadcast(GetMockAliveNotification()); eventSignal.WaitOne(1000); } Assert.IsFalse(receivedNotification); }
public void DeviceLocator_Notifications_SearchResponseUsesSharedMaxAge() { var server = new MockCommsServer(); var deviceLocator = new MockDeviceLocator(server); var publishedDevice = CreateDeviceTree(); publishedDevice.CacheLifetime = TimeSpan.FromMinutes(30); DiscoveredSsdpDevice device = null; using (var eventSignal = new System.Threading.AutoResetEvent(false)) { deviceLocator.DeviceAvailable += (sender, args) => { device = args.DiscoveredDevice; eventSignal.Set(); }; var t = deviceLocator.SearchAsync(TimeSpan.FromSeconds(3)); System.Threading.Thread.Sleep(500); server.MockReceiveMessage(GetMockSearchResponseWithCustomCacheHeader(publishedDevice, publishedDevice.Udn, String.Format("CACHE-CONTROL: public, s-maxage={0}", publishedDevice.CacheLifetime.TotalSeconds))); eventSignal.WaitOne(10000); var results = t.GetAwaiter().GetResult(); Assert.IsNotNull(results); Assert.IsTrue(results.Any()); Assert.AreEqual(device.CacheLifetime, results.First().CacheLifetime); } }