Ejemplo n.º 1
0
 static public void StartListen(GrblCore Core)
 {
     C  = Core;
     EV = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, "LaserGRBL syncro event");
     TH = new System.Threading.Thread(DoTheJob);
     TH.Start();
 }
Ejemplo n.º 2
0
        public static void OE_App_3_0_2_0(System.Threading.EventWaitHandle evt)
        {
            Program.logIt("OE_App_3_0_2_0: ++");
            Process app = start_app();

            if (app != null)
            {
                Program.logIt($"OE_App_3_0_2_0: App started, {app.MainWindowTitle}");
                // to start the process post message WM_COMMAND, 0x3C(0x3D), 0
                System.Threading.Thread.Sleep(5000);
                app.Refresh();
                SetForegroundWindow(app.MainWindowHandle);
                IntPtr mainWnd = app.MainWindowHandle;
                Program.logIt($"OE_App_3_0_2_0: send message to {app.MainWindowTitle}({app.MainWindowHandle}), 0x111,0x3c,0");
                PostMessage(app.MainWindowHandle, WM_COMMAND, 0x3c, 0);
                IntPtr topWnd = GetDesktopWindow();
                Program.logIt($"OE_App_3_0_2_0: desktop Wnd: {topWnd}");
                evt.WaitOne();
                Program.logIt($"OE_App_3_0_2_0: recv terminate event.");
                app.Refresh();
                Program.logIt($"OE_App_3_0_2_0: send message to {app.MainWindowTitle}({app.MainWindowHandle}), 0x111,0x3d,0");
                PostMessage(app.MainWindowHandle, WM_COMMAND, 0x3d, 0);
                System.Threading.Thread.Sleep(5000);
                app.CloseMainWindow();
                app.WaitForExit(3000);
                if (!app.HasExited)
                {
                    app.Kill();
                }
            }
            Program.logIt("OE_App_3_0_2_0: --");
        }
Ejemplo n.º 3
0
        static void Main()
        {
            bool InstantExist;

            InstantRunEvent = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, "BatchDomainTools#MutexXKFNDHBEUF93JFBSWSX", out InstantExist);
            if (!InstantExist)
            {
                try
                {
                    IntPtr hWnd = BatchDomainTools.WebPanelCommons.NativeMethods.FindWindow(null, "Batch Domain Tools");
                    if (0L != hWnd.ToInt64())
                    {
                        BatchDomainTools.WebPanelCommons.NativeMethods.SendMessage(hWnd, 0x0112, (IntPtr)0xF120, IntPtr.Zero);
                        BatchDomainTools.WebPanelCommons.NativeMethods.SetForegroundWindow(hWnd);
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.Write(e, "Exception");
                }
                Application.Exit();
                return;
            }
            Setting.LoadSetting();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            /*if (System.IO.File.Exists(Setting.ConfigFileName))
             *  Setting.LoadSetting(); */
            Application.Run(new MainForm());
        }
Ejemplo n.º 4
0
 public void Write(String Data)
 {
     try
     {
         LockerForReaders.Reset();
         System.Threading.EventWaitHandle[] handles = null;
         lock (singletoneLocker)// Запрещаем другим потокам добавлять(удалять) читателей пока мы с ними работаем
         {
             handles = new System.Threading.EventWaitHandle[readers.Count()];
             int i = 0;
             foreach (Reader r in readers)
             {
                 handles[i] = r.LockerForWriter;
                 i++;
             }
         }
         if (handles.Length == 0)
         {
             return;
         }
         System.Threading.EventWaitHandle.WaitAll(handles);
         Console.WriteLine("Что-то пишем далее что-то делаем в течении секунды (в это время никто ничего не имеет права ни читать ни писать)");
         data = "--";
         for (int i = 0; i < 10; i++)
         {
             data += i.ToString();
             System.Threading.Thread.Sleep(50);
         }
         data += "--";
     }
     finally
     {
         LockerForReaders.Set();
     }
 }
Ejemplo n.º 5
0
 static void Main(string[] args)
 {
     System.Configuration.Install.InstallContext _args = new System.Configuration.Install.InstallContext(null, args);
     if (_args.IsParameterTrue("start-service"))
     {
         bool own = false;
         System.Threading.EventWaitHandle evt = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset, NAME, out own);
         if (own)
         {
             // download db
             //Task.Run(() => download_imei2model());
             start(evt);
         }
         else
         {
             // already running.
         }
     }
     else if (_args.IsParameterTrue("kill-service"))
     {
         try
         {
             System.Threading.EventWaitHandle evt = System.Threading.EventWaitHandle.OpenExisting(NAME);
             evt.Set();
         }
         catch (Exception) { }
     }
     else
     {
     }
 }
Ejemplo n.º 6
0
        public static void Test()
        {
            Console.WriteLine("++++++++++++++++WeeklyWorkSheetTest++++++++++++++++++");
            using (WaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset))
            {
                DateTime beginTime = DateTime.Now.AddSeconds(-2);
                DateTime endTime   = DateTime.Now.AddSeconds(3);
                using (WeeklyWorkSheet ws = new WeeklyWorkSheet())
                {
                    ws.DayOfWeekWorkSheetItemBeginning += new EventHandler <DayOfWeekWorkSheetItemBeginningEventArgs>(ws_DayOfWeekWorkSheetItemBeginning);
                    ws.DayOfWeekWorkSheetItemEnding    += new EventHandler <DayOfWeekWorkSheetItemEndingEventArgs>(ws_DayOfWeekWorkSheetItemEnding);

                    ws.Monday.Items.Add(beginTime, endTime);
                    ws.Monday.Items.Add(beginTime.AddSeconds(10), endTime.AddSeconds(10));
                    ws.CopyToAll(DayOfWeek.Monday);
                    int i = 0;
                    while (i < ws.Monday.Items.Count)
                    {
                        i++;
                        Console.WriteLine("====================================");
                        Console.WriteLine("Waiting for Beginning");
                        WaitHandle.WaitOne();
                        Console.WriteLine("Waiting for Ending");
                        WaitHandle.WaitOne();
                    }
                    Console.WriteLine("Press enter to continue.");
                    Console.ReadKey();
                }
            }
        }
Ejemplo n.º 7
0
 public GcMachine()
 {
     userStack        = new Varible[stackSize];
     systemStack      = new int[stackSize];
     userStackTop     = 0;
     systemStackTop   = 0;
     userStackBase    = 0;
     code             = new Instruction[codeSize];
     globalMap        = new Dictionary <string, Varible>();
     stringMap        = new List <string>();
     locals           = new Dictionary <string, List <string> >();
     wantPause        = false;
     flags            = MachineFlags.MACHINE_FLAGS_NONE;
     breakpointList   = new Dictionary <int, bool>();
     functionTable    = new SortedDictionary <int, string>();
     inSystemFunction = null;
     lineCode         = new int[maxLines];
     executeEvent     = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset);
     for (int i = 0; i < maxLines; ++i)
     {
         lineCode[i] = -1;
     }
     status          = MachineStatus.MACHINE_STATUS_PAUSED;
     compileComplete = false;
 }
Ejemplo n.º 8
0
 public static void Test()
 {
     Console.WriteLine("++++++++++++++++ProgrammeTest++++++++++++++++++");
     using (WaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset))
     {
         DateTime triggerTime = DateTime.Now.AddSeconds(2);
         using (Programme prog = new Programme())
         {
             prog.Reminding += new EventHandler <ProgrammeRemindingEventArgs>(prog_Reminding);
             prog.Items.Add("1", new PlanTime(triggerTime.Hour, triggerTime.Minute, triggerTime.Second), "新闻联播");
             prog.Items.Add(new ProgrammeItem("2", new PlanTime(triggerTime.AddSeconds(2)), "二人转 001"));
             prog.Items.Add("3", new PlanTime(triggerTime.AddDays(1)), "二人转 002");
             DateTime date = DateTime.Now.Date;
             ReadOnlyCollection <ProgrammeItem> collection = prog.GetDateProgrammeItems(date);
             Console.WriteLine("Today's Programme");
             foreach (var item in collection)
             {
                 Console.WriteLine("{0} {1}", item.Content, item.PlannedTime.ToDateTime(date));
             }
             Console.WriteLine("====================================");
             Console.WriteLine("Waiting for {0}", prog.Items["1"].Content);
             WaitHandle.WaitOne();
             Console.WriteLine("Waiting for {0}", prog.Items["2"].Content);
             WaitHandle.WaitOne();
             Console.WriteLine("Press enter to continue.");
             Console.ReadKey();
         }
     }
 }
Ejemplo n.º 9
0
        static void start(System.Threading.EventWaitHandle quit)
        {
            var appSettings = ConfigurationManager.AppSettings;

            try
            {
                Uri            baseAddress = new Uri(string.Format("http://localhost:{0}/", appSettings["port"]));
                WebServiceHost svcHost     = new WebServiceHost(typeof(Program), baseAddress);
                WebHttpBinding b           = new WebHttpBinding();
                b.Name = NAME;
                b.HostNameComparisonMode = HostNameComparisonMode.Exact;
                svcHost.AddServiceEndpoint(typeof(IModelLookupWebService), b, "");
                logIt("WebService is running");
                svcHost.Open();
                download_imei2model();
                loadDB();
                quit.WaitOne();
                //System.Console.WriteLine("Press any key to stop.");
                //System.Console.ReadKey();
                svcHost.Close();
            }
            catch (Exception ex)
            {
                logIt(ex.Message);
            }
        }
Ejemplo n.º 10
0
            internal void start()
            {
                kname = parent.kbasename + "_thread" + threadnum.ToString();

                hmap = SlaveMemory.CreateFileMapping(SlaveMemory.INVALID_HANDLE_VALUE, IntPtr.Zero, SlaveMemory.PAGE_READWRITE, 0, 1 + 8 + 4 + parent.packetsize, kname + "_block" + parent.slavenum.ToString());
                if (IntPtr.Zero == hmap)
                {
                    throw new SlaveMemoryException("Unable to opeb shared memory communication buffer");
                }

                pview = SlaveMemory.MapViewOfFile(hmap, SlaveMemory.FILE_MAP_ALL_ACCESS, 0, 0, 0);
                if (IntPtr.Zero == pview)
                {
                    SlaveMemory.CloseHandle(hmap);
                    hmap = IntPtr.Zero;
                    throw new SlaveMemoryException("Unable to map shared memory communication buffer");
                }

                this.ewh = System.Threading.EventWaitHandle.OpenExisting(kname + "_event" + parent.slavenum.ToString());
                if (parent.usereturnevent)
                {
                    this.ewhreturn = System.Threading.EventWaitHandle.OpenExisting(kname + "_returnevent" + parent.slavenum.ToString());
                }

                this.thread = new System.Threading.Thread(new System.Threading.ThreadStart(slavethreadproc));
                this.thread.Start();
            }
Ejemplo n.º 11
0
 public Reader(Manager m, Int32 Number)
 {
     number = Number;
     manager = m;
     LockerForWriter = new System.Threading.EventWaitHandle(true, System.Threading.EventResetMode.ManualReset);
     timer = new System.Threading.Timer(Read, null, 100, 100);
 }
Ejemplo n.º 12
0
        private void btnSearchKey_Click(object sender, EventArgs e)
        {
            if (RedisClient == null)
            {
                DoConnection();
            }
            try
            {
                this.treeKeys.Nodes.Clear();
                System.Threading.EventWaitHandle waitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
                List <string> keys = null;
                new Task(() =>
                {
                    keys = RedisClient.SearchKeys(txtPattern.Text);
                    waitHandle.Set();
                }).Start();
                if (!waitHandle.WaitOne(RedisClient.SendTimeout))
                {
                    RedisClient.Dispose();
                    RedisClient = null;
                    throw new Exception("search keys timeout!");
                }
                NestedHash keysTree = new NestedHash();
                foreach (string key in keys)
                {
                    string[]   keySegments = key.Split(':');
                    NestedHash pHash       = keysTree;   // 指针
                    string     pKeySegment = "";         // 指针
                    for (int i = 0; i < keySegments.Length; i++)
                    {
                        string keySegment = keySegments[i];
                        if (i > 0)
                        {
                            if (pHash[pKeySegment] == null)
                            {
                                NestedHash hash = new NestedHash();
                                pHash[pKeySegment] = hash;
                                pHash = hash;
                            }
                            else
                            {
                                pHash = pHash[pKeySegment] as NestedHash;
                            }
                        }

                        if (!pHash.ContainsKey(keySegment))
                        {
                            pHash.Add(keySegment, null);
                        }

                        pKeySegment = keySegment;
                    }
                }
                BuildTree(this.treeKeys.Nodes, keysTree);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 13
0
 static void handle_QueryISP_Command(System.Collections.Specialized.StringDictionary args)
 {
     if (args.ContainsKey("start-service"))
     {
         bool own;
         System.Threading.EventWaitHandle e = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, eventName, out own);
         if (own)
         {
             AVIAGetPhoneSize.start(e);
         }
         else
         {
             // device monitor already started.
         }
     }
     else if (args.ContainsKey("kill-service"))
     {
         try
         {
             System.Threading.EventWaitHandle e = System.Threading.EventWaitHandle.OpenExisting(eventName);
             e.Set();
         }
         catch (Exception) { }
     }
 }
Ejemplo n.º 14
0
        public override void RunInGuiThread(System.Action d)
        {
            if (alreadyInGuiThread)
            {
                Console.WriteLine();
                Console.WriteLine("WARNING: You called RunInGuiThread nestedly.");
                d();
                return;
            }
            alreadyInGuiThread = true;

            try {
                System.Threading.EventWaitHandle h = guiThread.CallDelegInMainLoop(d);
                h.WaitOne();
                h.Close();
                if (guiThread.ExceptionHappened != null)
                {
                    throw guiThread.ExceptionHappened;
                }
            }
            finally {
                alreadyInGuiThread = false;
            }
            System.Threading.Thread.Sleep(2000);
        }
Ejemplo n.º 15
0
 public ProducerAndConsumer()
 {
     for (int i = 0; i < NUM_CONSUMER; ++i)
     {
         event_consumers[i] = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
     }
 }
Ejemplo n.º 16
0
 public static void startup(System.Collections.Specialized.StringDictionary args)
 {
     Program.logIt("OEControl::startup: ++");
     if (args.ContainsKey("start"))
     {
         bool own;
         System.Threading.EventWaitHandle evt = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset, EVENT_NAME, out own);
         if (!own)
         {
             // OE app already running.
             Program.logIt("OEControl::startup: app already running");
         }
         else
         {
             OEControl.OE_App_3_0_2_0(evt);
         }
     }
     else if (args.ContainsKey("stop"))
     {
         try
         {
             System.Threading.EventWaitHandle evt = System.Threading.EventWaitHandle.OpenExisting(EVENT_NAME);
             evt.Set();
         }
         catch (Exception) { }
     }
     Program.logIt("OEControl::startup: --");
 }
Ejemplo n.º 17
0
 public static void Test()
 {
     using (WaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset))
     {
         //Plan_Test();
         PlanPeriod_Test();
     }
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Disposing the object
 /// </summary>
 public void Dispose()
 {
     if (CmdSignal != null)
     {
         CmdSignal.Close();
         CmdSignal = null;
     }
 }
Ejemplo n.º 19
0
 /// <summary>
 /// 释放调度器
 /// </summary>
 public virtual void Dispose()
 {
     StopWait();
     AddJobWaitHandle = null;
     LoopWaitHandle   = null;
     ExecuteThread    = null;
     StatusFlag       = -1;
 }
Ejemplo n.º 20
0
 public IClient(NetConnection conn, Game gameInstance)
     : base(conn,gameInstance)
 {
     Que = new System.Collections.ObjectModel.Collection<qmsg>();
     InternalQue = new System.Collections.ObjectModel.Collection<qmsg>();
     Connection = conn;
     WH = new System.Threading.AutoResetEvent(false);
 }
Ejemplo n.º 21
0
 static DeviceInformation()
 {
     stateHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset);
     _manager = new CBCentralManager();
     //_manager.RetrievedConnectedPeripherals += _manager_RetrievedConnectedPeripherals;
     //_manager.RetrievedPeripherals += _manager_RetrievedPeripherals;
     _manager.UpdatedState += _manager_UpdatedState;
     _manager.DiscoveredPeripheral += _manager_DiscoveredPeripheral;
 }
Ejemplo n.º 22
0
 public SettingTasks(PLCData store)
 {
     wait = new System.Threading.EventWaitHandle[4];//LDC 6.....4
     for (int i = 0; i < wait.Length; i++)
     {
         wait[i] = new System.Threading.EventWaitHandle(true, System.Threading.EventResetMode.ManualReset);
     }
     this.Store = store;
     this.Store.Device.ResultGot4Custom += Device_ResultGot4Custom;
 }
Ejemplo n.º 23
0
 private ConfigWatcher()
 {
     this.configDictionary = new Dictionary <string, IConfig>();
     //
     this.waitEventHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
     //
     this.thread = new System.Threading.Thread(this.Processor);
     this.thread.IsBackground = true;
     this.thread.Start();
 }
Ejemplo n.º 24
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            bool createdNew;

            mutex = new System.Threading.Mutex(true, Res.Resources.GetRes().GetSoftServicePCName(), out createdNew);
            System.Threading.EventWaitHandle eventWaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset, Res.Resources.GetRes().GetSoftServicePCName() + Res.Resources.GetRes().GetSoftServicePCName());



            if (createdNew)
            {
                // Spawn a thread which will be waiting for our event
                var thread = new System.Threading.Thread(
                    () =>
                {
                    while (eventWaitHandle.WaitOne())
                    {
                        lock (TheLock)
                        {
                            Form defaultForm = Application.OpenForms.Cast <Form>().Where(x => null != x.Tag && x.Tag.ToString() == "Main").FirstOrDefault();

                            if (null != defaultForm)
                            {
                                defaultForm.BeginInvoke((Action)(() => BringToForeground(defaultForm)));
                            }
                        }
                    }
                });

                // It is important mark it as background otherwise it will prevent app from exiting.
                thread.IsBackground = true;

                thread.Start();

                //注册错误
                Application.ThreadException += Application_ThreadException;
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                //加载日志
                Resources.GetRes().LoadLog();
                //字体效果(为XP开启)
                FontSmoothing.OpenFontEffect();

                Resources.GetRes().SetDeviceType((long)1);
                Application.Run(new LoginWindow());
                mutex.ReleaseMutex();
            }
            // Notify other instance so it could bring itself to foreground.
            eventWaitHandle.Set();

            // Terminate this instance.
            Environment.Exit(0);
        }
Ejemplo n.º 25
0
 public static void ChangeHostState(String scope, String state)
 {
     try
     {
         System.Threading.EventWaitHandle evt = System.Threading.EventWaitHandle.OpenExisting(Solution.HostKillerName(scope, state));
         evt.Set();
     }
     catch (Exception)
     {
     }
 }
Ejemplo n.º 26
0
		public Event(bool autoReset, bool signaled)
		{
			if (autoReset)
			{
				m_event = new System.Threading.AutoResetEvent(signaled);
			}
			else
			{
				m_event = new System.Threading.ManualResetEvent(signaled);
			}
		}
Ejemplo n.º 27
0
 public VisitorThreadInfo(Udbus.Serialization.UdbusConnector connector,
                          Udbus.Core.IUdbusMessageVisitor visitor,
                          Udbus.Core.DbusMessageReceiverPool pool,
                          System.Threading.EventWaitHandle stop,
                          System.IO.TextWriter output)
 {
     this.connector = connector;
     this.visitor   = visitor;
     this.pool      = pool;
     this.stop      = stop;
     this.output    = output;
 }
Ejemplo n.º 28
0
 public static Task <T> ToTaskAsync <T>(this IPushObservable <T> observable)
 {
     return(Task.Run(() =>
     {
         T latestValue = default(T);
         var mtx = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
         var disp = observable.Subscribe((v) => latestValue = v, () => mtx.Set());
         mtx.WaitOne();
         disp.Dispose();
         return latestValue;
     }));
 }
Ejemplo n.º 29
0
 public void PlayAsync(string url)
 {
     System.Threading.EventWaitHandle wait = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
     Task.Factory.StartNew(() =>
     {
         System.Media.SoundPlayer player = new System.Media.SoundPlayer(url);
         player.PlaySync();
         wait.Set();
     }).ContinueWith(x =>
     {
         wait.WaitOne();
     });
 }
Ejemplo n.º 30
0
        public void EnableUnenableRouterTest()
        {
            var hEvent      = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset);
            var pOverLapped = new System.Threading.NativeOverlapped {
                EventHandle = hEvent.SafeWaitHandle.DangerousGetHandle()
            };

            unsafe
            {
                Assert.That(EnableRouter(out _, &pOverLapped), Is.Zero.Or.EqualTo(Win32Error.ERROR_IO_PENDING));
                Assert.That(UnenableRouter(&pOverLapped, out _), Is.Zero.Or.EqualTo(Win32Error.ERROR_IO_PENDING));
            }
        }
Ejemplo n.º 31
0
 public void PlayAsync(string url)
 {
     System.Threading.EventWaitHandle wait = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
     Task.Factory.StartNew(() =>
     {
         System.Media.SoundPlayer player = new System.Media.SoundPlayer(url);
         player.PlaySync();
         wait.Set();
     }).ContinueWith(x =>
     {
         wait.WaitOne();
     });
 }
Ejemplo n.º 32
0
 private void commitPendingChanges(Lynx.PropertySets.Workspace workspace)
 {
     sessionLogger.Log("commit pending changes.");
     using (var eventWaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset))
     {
         workspace.commit(System.DateTime.Now.ToString(), (error, commitNode) => { if (error != null)
                                                                                   {
                                                                                       System.Windows.Forms.MessageBox.Show(error.what()); sessionLogger.Log("error: " + error.what());
                                                                                   }
                                                                                   eventWaitHandle.Set(); });
         eventWaitHandle.WaitOne();
     }
 }
Ejemplo n.º 33
0
        static void Main(string[] args)
        {
            System.Threading.EventWaitHandle systemweit = new System.Threading.EventWaitHandle(false,
                                                                                               System.Threading.EventResetMode.ManualReset,
                                                                                               "MeineSystemweite");

            Console.WriteLine("2: Gib irgend was ein !");
            Console.ReadLine();


            systemweit.Set();

            Console.WriteLine("2: Habe Systemweit gesetzt");
        }
Ejemplo n.º 34
0
        public RecordHolder(ClusteredFile file, UInt32 RecordNo, Record record)
        {
            RecordFinalized = new System.Threading.EventWaitHandle(false,
                                                                   System.Threading.EventResetMode.ManualReset);
#if DUMP_FINALIZE
            System.Diagnostics.Trace.WriteLine(file.mOriginalFile + " New RecordHolder for #" + RecordNo);
            System.Diagnostics.Debug.Assert(record != null);
#endif

            mFile     = file;
            mRecordNo = RecordNo;
            MakeWeakRef(record);
            mHold = record;
        }
Ejemplo n.º 35
0
        public RecordHolder(ClusteredFile file, UInt32 RecordNo, Record record)
        {
            RecordFinalized = new System.Threading.EventWaitHandle(false,
                System.Threading.EventResetMode.ManualReset);
            #if DUMP_FINALIZE
            System.Diagnostics.Trace.WriteLine(file.mOriginalFile + " New RecordHolder for #" + RecordNo);
            System.Diagnostics.Debug.Assert(record != null);
            #endif

            mFile = file;
            mRecordNo = RecordNo;
            MakeWeakRef(record);
            mHold = record;
        }
Ejemplo n.º 36
0
 public UuidLock(string uuid)
 {
     this.uuid = uuid;
     lock (globalLock)
     {
         if (!Locks.ContainsKey(uuid))
         {
             Locks.Add(uuid, new LockItem());
         }
         var item = Locks[uuid];
         item.count++;
         ev = item.ev;
     }
     ev.WaitOne();
 }
Ejemplo n.º 37
0
 /// <summary>
 /// Constructor for initialization and acquireing locks
 /// </summary>
 /// <param name="key"></param>
 public KeyLock(string key)
 {
     this.key = key;
     lock (globalLock)
     {
         if (!Locks.ContainsKey(key))
         {
             Locks.Add(key, new LockItem());
         }
         var item = Locks[key];
         item.count++;
         ev = item.ev;
     }
     ev.WaitOne();
 }
Ejemplo n.º 38
0
        public override bool Execute()
        {
            System.Threading.EventWaitHandle handle = new System.Threading.EventWaitHandle(
                true, System.Threading.EventResetMode.AutoReset, m_Name);

            if (m_Lock)
            {
                handle.WaitOne();
                handle.Reset();
            }
            else
            {
                handle.Set();
            }

            return true;
        }
Ejemplo n.º 39
0
 public void DanglingWindowMessage()
 {
     using (OuterTest nuf = new OuterTest())
     {
         Form f = new Form();
         f.Show();
         System.Threading.EventWaitHandle w = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
         System.Threading.ThreadPool.QueueUserWorkItem(delegate(object o)
         {
             f.BeginInvoke(new MethodInvoker(delegate()
             {
                 MessageBox.Show("", "Blah");
             }));
             w.Set();
         });
         w.WaitOne();
         Assert.Throws<FormsTestAssertionException>(() => nuf.Verify());
     }
 }
Ejemplo n.º 40
0
        public int Execute()
        {
            try
            {
                Action<string> log = text => { if(!settings.Quiet) Console.Out.WriteLine(text); };

                var wait = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);

                using(var client = new WebClientWithInfo())
                {
                    client.Headers[HttpRequestHeader.UserAgent] = settings.Http.UserAgent;
                    client.Headers[HttpRequestHeader.Accept] = "*/*";

                    client.GotResponse += (object _, WebClientWithInfo.ResponseEventArgs e) => {
                        log("Got response...");
                        log("Length: {0}".With(e.Response.ContentLength > -1 ? e.Response.ContentLength.ToString() : "unspecfied"));
                        log("Saving to: '{0}'\n".With(settings.Download.OutputDocument));
                    };

                    client.DownloadProgressChanged += (object _, DownloadProgressChangedEventArgs e) => {
                        log("progress: {0}/{1} ({2}%)".With(e.BytesReceived, e.TotalBytesToReceive, e.ProgressPercentage));
                    };

                    client.DownloadDataCompleted += (_, e) => wait.Set();

                    settings.Urls.Each(url => {
                        client.DownloadDataAsync(new Uri(url));
                        // update progressbar etc
                        wait.WaitOne();
                    });
                }

                return 0;
            }
            catch (Exception ex)
            {
                if(!settings.Quiet)
                    Console.Error.WriteLine(ex.Message);
                return 1;
            }
        }
Ejemplo n.º 41
0
		/// <summary>Starts the installer program, when all presumtions are fullfilled.</summary>
		/// <param name="isAltaxoCurrentlyStarting">If set to <c>true</c>, Altaxo will be restarted after the installation is done.</param>
		/// <param name="commandLineArgs">Original command line arguments. Can be <c>null</c> when calling this function on shutdown.</param>
		/// <returns>True if the installer program was started. Then Altaxo have to be shut down immediately. Returns <c>false</c> if the installer program was not started.</returns>
		public static bool Run(bool isAltaxoCurrentlyStarting, string[] commandLineArgs)
		{
			var updateSettings = Current.PropertyService.GetValue(Altaxo.Settings.AutoUpdateSettings.PropertyKeyAutoUpdate, Main.Services.RuntimePropertyKind.UserAndApplicationAndBuiltin, () => new Altaxo.Settings.AutoUpdateSettings());

			var installationRequested = (isAltaxoCurrentlyStarting && updateSettings.InstallAtStartup) || (!isAltaxoCurrentlyStarting && updateSettings.InstallAtShutdown);
			if (!installationRequested)
				return false;

			bool loadUnstable = updateSettings.DownloadUnstableVersion;

			FileStream versionFileStream = null;
			FileStream packageStream = null;

			// try to lock the version file in the download directory, thus no other process can modify it
			try
			{
				var downloadFolder = PackageInfo.GetDownloadDirectory(loadUnstable);
				var versionFileName = Path.Combine(downloadFolder, PackageInfo.VersionFileName);

				versionFileStream = new FileStream(versionFileName, FileMode.Open, FileAccess.Read, FileShare.Read);

				var info = PackageInfo.GetPresentDownloadedPackage(versionFileStream, downloadFolder, out packageStream);

				if (null == info || null == packageStream)
					return false;

				var entryAssembly = System.Reflection.Assembly.GetEntryAssembly();
				var entryAssemblyVersion = entryAssembly.GetName().Version;

				if (info.Version <= entryAssemblyVersion)
					return false; // no need to update

				if (updateSettings.ConfirmInstallation)
				{
					var question = string.Format(
						"A new Altaxo update is available (from current version {0} to new {1} version {2}).\r\n\r\n" +
						"If you don't want to have auto updates, please deactivate them by choosing 'Tools'->'Options' menu in Altaxo.\r\n" +
						"\r\n" +
					"Do you want to update to {1} version {2} now?", entryAssemblyVersion, PackageInfo.GetStableIdentifier(info.IsUnstableVersion).ToLower(), info.Version);

					if (false == Current.Gui.YesNoMessageBox(question, "Altaxo update available", true))
						return false; // user don't want to update
				}

				// copy the Updater executable to the download folder
				var entryAssemblyFolder = Path.GetDirectoryName(entryAssembly.Location);
				var installerFullSrcName = Path.Combine(entryAssemblyFolder, UpdateInstallerFileName);
				var installerFullDestName = Path.Combine(downloadFolder, UpdateInstallerFileName);
				File.Copy(installerFullSrcName, installerFullDestName, true);

				// both the version file and the package stream are locked now
				// so we can start the updater program

				var eventName = System.Guid.NewGuid().ToString();
				var waitForRemoteStartSignal = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, eventName);

				var processInfo = new System.Diagnostics.ProcessStartInfo();
				processInfo.FileName = installerFullDestName;
				StringBuilder stb = new StringBuilder();
				stb.AppendFormat(System.Globalization.CultureInfo.InvariantCulture,
					"\"{0}\"\t\"{1}\"\t{2}\t{3}\t{4}\t\"{5}\"",
					eventName,
					packageStream.Name,
					updateSettings.ShowInstallationWindow ? 1 : 0,
					updateSettings.InstallationWindowClosingTime,
					isAltaxoCurrentlyStarting ? 1 : 0,
					entryAssembly.Location);
				if (isAltaxoCurrentlyStarting && commandLineArgs != null && commandLineArgs.Length > 0)
				{
					foreach (var s in commandLineArgs)
						stb.AppendFormat("\t\"{0}\"", s);
				}
				processInfo.Arguments = stb.ToString();
				processInfo.CreateNoWindow = false;
				processInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;

				// Start the updater program
				var process = System.Diagnostics.Process.Start(processInfo);

				for (; ; )
				{
					// we wait until the update program signals that it has now taken the VersionInfo file
					if (waitForRemoteStartSignal.WaitOne(100))
						break;
					if (process.HasExited)
						return false; // then something has gone wrong or the user has closed the window
				}

				return true;
			}
			catch (Exception)
			{
				return false;
			}
			finally
			{
				if (null != packageStream)
					packageStream.Close();
				if (null != versionFileStream)
					versionFileStream.Close();
			}
		}
Ejemplo n.º 42
0
		public void Dispose()
		{
			m_event.Close();
			m_event = null;
		}
Ejemplo n.º 43
0
        public LibsnesApi(string exePath)
        {
            //make sure we've checked this exe for OKness.. the dry run should keep us from freezing up or crashing weirdly if the external process isnt correct
            if (!okExes.Contains(exePath))
            {
                bool ok = DryRun(exePath);
                if (!ok)
                    throw new InvalidOperationException(string.Format("Couldn't launch {0} to run SNES core. Not sure why this would have happened. Try redownloading BizHawk first.", Path.GetFileName(exePath)));
                okExes.Add(exePath);
            }

            InstanceName = "libsneshawk_" + Guid.NewGuid().ToString();

            #if DEBUG
            //use this to get a debug console with libsnes output
            InstanceName = "console-" + InstanceName;
            #endif

            var pipeName = InstanceName;

            mmf = MemoryMappedFile.CreateNew(pipeName, 1024 * 1024);
            mmva = mmf.CreateViewAccessor();
            mmva.SafeMemoryMappedViewHandle.AcquirePointer(ref mmvaPtr);

            pipe = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None, 1024 * 1024, 1024);

            //slim chance this might be useful sometimes:
            //http://stackoverflow.com/questions/2590334/creating-a-cross-process-eventwaithandle
            //create an event for the child process to monitor with a watchdog, to make sure it terminates when the emuhawk process terminates.
            //NOTE: this is alarming! for some reason .net releases this event when it gets finalized, instead of when i (dont) dispose it.
            bool createdNew;
            watchdogEvent = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset, InstanceName + "-event", out createdNew);

            process = new Process();
            process.StartInfo.WorkingDirectory = Path.GetDirectoryName(exePath);
            process.StartInfo.FileName = exePath;
            process.StartInfo.Arguments = pipeName;
            process.StartInfo.ErrorDialog = true;
            process.Start();

            //TODO - start a thread to wait for process to exit and gracefully handle errors? how about the pipe?

            pipe.WaitForConnection();

            rbuf = new IPCRingBuffer();
            wbuf = new IPCRingBuffer();
            rbuf.Allocate(1024);
            wbuf.Allocate(1024);
            rbufstr = new IPCRingBufferStream(rbuf);
            wbufstr = new IPCRingBufferStream(wbuf);

            rstream = new SwitcherStream();
            wstream = new SwitcherStream();

            rstream.SetCurrStream(pipe);
            wstream.SetCurrStream(pipe);

            brPipe = new BinaryReader(rstream);
            bwPipe = new BinaryWriter(wstream);

            WritePipeMessage(eMessage.eMessage_SetBuffer);
            bwPipe.Write(1);
            WritePipeString(rbuf.Id);
            WritePipeMessage(eMessage.eMessage_SetBuffer);
            bwPipe.Write(0);
            WritePipeString(wbuf.Id);
            bwPipe.Flush();
        }
Ejemplo n.º 44
0
 internal LockerEvent()
 {
     ev = new System.Threading.ManualResetEvent(false);
     next = null;
 }
Ejemplo n.º 45
0
		public MainWindow(UpdateMonitor InUpdateMonitor, string InSqlConnectionString, string InDataFolder, EventWaitHandle ActivateEvent, bool bInRestoreStateOnLoad, string InOriginalExecutableFileName, string InProjectFileName)
		{
			InitializeComponent();

			NotifyMenu_OpenUnrealGameSync.Font = new Font(NotifyMenu_OpenUnrealGameSync.Font, FontStyle.Bold);

            if (Application.RenderWithVisualStyles) 
            { 
				SelectedItemRenderer = new VisualStyleRenderer("Explorer::ListView", 1, 3);
				TrackedItemRenderer = new VisualStyleRenderer("Explorer::ListView", 1, 2); 
			}

			UpdateMonitor = InUpdateMonitor;
			ActivationListener = new ActivationListener(ActivateEvent);
			SqlConnectionString = InSqlConnectionString;
			DataFolder = InDataFolder;
			bRestoreStateOnLoad = bInRestoreStateOnLoad;
			OriginalExecutableFileName = InOriginalExecutableFileName;
			
			Log = new BoundedLogWriter(Path.Combine(DataFolder, "UnrealGameSync.log"));
			Log.WriteLine("Application version: {0}", Assembly.GetExecutingAssembly().GetName().Version);
			Log.WriteLine("Started at {0}", DateTime.Now.ToString());

			Settings = new UserSettings(Path.Combine(DataFolder, "UnrealGameSync.ini"));
			if(!String.IsNullOrEmpty(InProjectFileName))
			{
				Settings.LastProjectFileName = InProjectFileName;
			}

			System.Reflection.PropertyInfo DoubleBufferedProperty = typeof(Control).GetProperty("DoubleBuffered", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
			DoubleBufferedProperty.SetValue(BuildList, true, null); 

			// force the height of the rows
			BuildList.SmallImageList = new ImageList(){ ImageSize = new Size(1, 20) };
			BuildList_FontChanged(null, null);
			BuildList.OnScroll += BuildList_OnScroll;

			Splitter.OnVisibilityChanged += Splitter_OnVisibilityChanged;
			
			UpdateTimer = new Timer();
			UpdateTimer.Interval = 30;
			UpdateTimer.Tick += TimerCallback;

			BuildAfterSyncCheckBox.Checked = Settings.bBuildAfterSync;
			RunAfterSyncCheckBox.Checked = Settings.bRunAfterSync;
			OpenSolutionAfterSyncCheckBox.Checked = Settings.bOpenSolutionAfterSync;
			Splitter.SetLogVisibility(Settings.bShowLogWindow);
			OptionsContextMenu_AutoResolveConflicts.Checked = Settings.bAutoResolveConflicts;
			OptionsContextMenu_UseIncrementalBuilds.Checked = Settings.bUseIncrementalBuilds;
			OptionsContextMenu_SyncPrecompiledEditor.Checked = Settings.bSyncPrecompiledEditor;
			
			UpdateCheckedBuildConfig();

			UpdateProjectList();
			UpdateSyncActionCheckboxes();
		}
Ejemplo n.º 46
0
        /**
         * Constructor.
         */
        public Encoder()
        {
            this.enableRecording = false;
            this.chopNumber = 0;
            this.chopLength = -1;

            this.choppingTimer = new System.Timers.Timer();
            this.choppingTimer.Elapsed += this.OnRecordTimeElapsed;
            this.archiveState = WMENC_ARCHIVE_STATE.WMENC_ARCHIVE_STOPPED;
            this.stateChangeWaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, string.Empty);
            this.archiveStateChangeWaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, string.Empty);

            // Audio and video sources
            this.audioSource = null;
            this.videoSource = null;

            // Windows Media Encoder
            this.wmEncoder = new WMEncoderClass();
            this.sourceGroup = (IWMEncSourceGroup2)this.wmEncoder.SourceGroupCollection.Add("SG_1");
            this.wmEncoderProfile = new WMEncProfile2();

            // For now, we only listen these events
            this.wmEncoder.OnStateChange += this.OnStateChange;
            this.wmEncoder.OnError += this.OnError;
            this.wmEncoder.OnArchiveStateChange += this.OnArchiveStateChange;

            // Set recording props.
            this.wmEncoder.EnableAutoArchive = false;
            this.wmEncoder.AutoIndex = false;

            // Set default profile values
            this.wmEncoderProfile.ValidateMode = true;
            this.wmEncoderProfile.ProfileName = "Windows Media Encoder Profile";
            this.wmEncoderProfile.ContentType = 17; // Audio + Video
            this.wmEncoderAudience = this.wmEncoderProfile.AddAudience(100000); // Initial bitrate = 100 kbps, will change automatically
            // when user sets video and audio params.
        }
Ejemplo n.º 47
0
		protected Window() :
			base(1024, 768, "", OpenTK.GameWindowFlags.Default, OpenTK.Graphics.GraphicsMode.Default, OpenTK.DisplayDevice.Default)
		{
			this.threadPool = this.CreateThreadPool("OpenGL", 8);
			Backend.Context.Current = this.Context = this.Context ?? Backend.Context.Current ?? this.CreateContext();
			this.redrawSignal = new System.Threading.EventWaitHandle(true, System.Threading.EventResetMode.AutoReset);
		}
Ejemplo n.º 48
0
 private Manager()
 {
     data = "";
     LockerForReaders = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset);
     readers = new List<Reader>();
 }
Ejemplo n.º 49
0
		/// <summary>Creates and then sets the specified event.</summary>
		/// <param name="eventName">Name of the event.</param>
		public static void SetEvent(string eventName)
		{
			_eventWaitHandle = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, eventName);
			_eventWaitHandle.Set();
		}
Ejemplo n.º 50
0
 public ProducerAndConsumer()
 {
     for (int i = 0; i < NUM_CONSUMER; ++i)
         event_consumers[i] = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);
 }
Ejemplo n.º 51
0
        private void InitializeServicesAfterProcessStarts()
        {
            try
            {
                if (!_jdwp)
                {
                    _ipcHandle.WaitOne();
                    _ipcHandle.Dispose();
                    _ipcHandle = null;
                }

                CreateProtocolServiceClient();
                _protocolService.Attach();

                OnAttachComplete(EventArgs.Empty);
            }
            catch (Exception e)
            {
                if (e.IsCritical())
                    throw;
            }
        }
Ejemplo n.º 52
0
 public WaveBufferList(int length, int size)
 {
     int i;
     wh_read = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset);
     wh_write = new System.Threading.EventWaitHandle(true, System.Threading.EventResetMode.ManualReset);
     WaveBuffer prev = null;
     array = new WaveBuffer[length];
     for (i = 0; i < length; i++)
     {
         WaveBuffer tmp = new WaveBuffer(size, prev);
         prev = tmp;
         if (i == 0)
         {
             first = tmp;
             read = tmp;
             write = tmp;
         }
         if (i == length - 1)
         {
             last = tmp;
             last.next = first;
             first.prev = last;
         }
         tmp.index = i;
         array[i] = tmp;
     }
 }
Ejemplo n.º 53
0
        public unsafe void BenchmarkIterationStop(string RunId, string BenchmarkName, int Iteration, bool Success)
        {
            if (ProfilerEvent == null)
            {
                try
                {
                    ProfilerEvent = System.Threading.EventWaitHandle.OpenExisting("Local\\BenchmarkActive");
                }
                catch (System.Exception e)
                {
                    throw e;
                }
            }

            ProfilerEvent.Reset();

            if (IsEnabled())
            {
                if (RunId == null)
                    RunId = "";

                int successInt = Success ? 1 : 0;
                fixed (char* pRunId = RunId)
                fixed (char* pBenchmarkName = BenchmarkName)
                {
                    EventData* data = stackalloc EventData[4];
                    data[0].Size = (RunId.Length + 1) * sizeof(char);
                    data[0].DataPointer = (IntPtr)pRunId;
                    data[1].Size = (BenchmarkName.Length + 1) * 2;
                    data[1].DataPointer = (IntPtr)pBenchmarkName;
                    data[2].Size = sizeof(int);
                    data[2].DataPointer = (IntPtr)(&Iteration);
                    data[3].Size = sizeof(int);
                    data[3].DataPointer = (IntPtr)(&successInt);
                    WriteEventCore(4, 4, data);
                }
            }

            if (_csvWriter != null)
                WriteCSV(BenchmarkName, iteration: Iteration, success: Success);

            System.GC.Collect();
            System.GC.WaitForPendingFinalizers();
        }
Ejemplo n.º 54
0
 public VisitorThreadInfo(Udbus.Serialization.UdbusConnector connector,
     Udbus.Core.IUdbusMessageVisitor visitor,
     Udbus.Core.DbusMessageReceiverPool pool,
     System.Threading.EventWaitHandle stop,
     System.IO.TextWriter output)
 {
     this.connector = connector;
     this.visitor = visitor;
     this.pool = pool;
     this.stop = stop;
     this.output = output;
 }
Ejemplo n.º 55
0
        public unsafe void BenchmarkIterationStart(string RunId, string BenchmarkName, int Iteration)
        {
            if (ProfilerEvent == null)
            {
                ProfilerEvent = new System.Threading.EventWaitHandle(false, System.Threading.EventResetMode.ManualReset, "Local\\BenchmarkActive");
            }

            ProfilerEvent.Set();

            if (_csvWriter != null)
                WriteCSV(BenchmarkName, iteration: Iteration);

            if (IsEnabled())
            {
                if (RunId == null)
                    RunId = "";

                fixed (char* pRunId = RunId)
                fixed (char* pBenchmarkName = BenchmarkName)
                {
                    EventData* data = stackalloc EventData[3];
                    data[0].Size = (RunId.Length + 1) * sizeof(char);
                    data[0].DataPointer = (IntPtr)pRunId;
                    data[1].Size = (BenchmarkName.Length + 1) * sizeof(char);
                    data[1].DataPointer = (IntPtr)pBenchmarkName;
                    data[2].Size = sizeof(int);
                    data[2].DataPointer = (IntPtr)(&Iteration);
                    WriteEventCore(3, 3, data);
                }
            }
        }