public void SetReset()
        {
            using (EventWaitHandle are = new EventWaitHandle(false, EventResetMode.AutoReset))
            {
                Assert.False(are.WaitOne(0));
                are.Set();
                Assert.True(are.WaitOne(0));
                Assert.False(are.WaitOne(0));
                are.Set();
                are.Reset();
                Assert.False(are.WaitOne(0));
            }

            using (EventWaitHandle mre = new EventWaitHandle(false, EventResetMode.ManualReset))
            {
                Assert.False(mre.WaitOne(0));
                mre.Set();
                Assert.True(mre.WaitOne(0));
                Assert.True(mre.WaitOne(0));
                mre.Set();
                Assert.True(mre.WaitOne(0));
                mre.Reset();
                Assert.False(mre.WaitOne(0));
            }
        }
    private int Run()
    {
        int iRet = -1;
        string sName = Common.GetUniqueName();
        //  open a semaphore with the same name as a mutex
        EventWaitHandle ewh = new EventWaitHandle(false, 
            EventResetMode.AutoReset, sName);
        try
        {
            using(Semaphore sem = Semaphore.OpenExisting(sName))
            {
            }
        }
        catch (WaitHandleCannotBeOpenedException)
        {
            //Expected	
            iRet = 100;
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught unexpected exception: " + 
                e.ToString());
        }

        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }
 public LargeIntervalTimerLeo()
 {
     m_interlock = new object();
     m_firstTime = DateTime.MinValue;
     m_interval = new TimeSpan(0, 0, 60);
     m_quitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
     TestCondition = -1;
 }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        this.cancelEvent = this.OpenEvent();
        this.settings = BXIBlockExportXmlSettings.Load();
        if (this.settings == null)
        {
            this.settings = new BXIBlockExportXmlSettings();
            this.settings.DestinationFile = BXConfigurationUtility.Options.UploadFolderPath +
                                    "export_file_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xml";
        }

        this.DestinationFile.Text = this.settings.DestinationFile;

        var siteTypes = TypeCB.Items;
        siteTypes.Clear();
        siteTypes.Add(new ListItem(GetMessageRaw("SelectItem.IBlockType"), string.Empty));

        foreach (var type in this.helper.AllTypes)
        {
            var name = this.helper.GetTypeName(type);
            siteTypes.Add(new ListItem(name, type.Id.ToString()));
        }

        int typeId = -1;
        if (!string.IsNullOrEmpty(settings.TypeName))
        {
            var item = TypeCB.Items.FindByValue(settings.TypeName);
            if (item != null)
            {
                item.Selected = true;
            }

            Int32.TryParse(settings.TypeName, out typeId);
        }

        this.UpdateBlocks(typeId);
        this.UpdateControls();

        if (!string.IsNullOrEmpty(settings.BlockName))
        {
            var item = BlockCB.Items.FindByValue(settings.BlockName);
            if (item != null)
            {
                item.Selected = true;
            }
        }

        this.Sections.SelectedIndex = (int)this.settings.SectionsMode;
        this.Elements.SelectedIndex = (int)this.settings.ElementsMode;
    }
	public static int Run()
	{
		var ewh = new EventWaitHandle(true, EventResetMode.AutoReset);
		var sw = new Stopwatch();
		
		if (!ewh.TestWaitOne(0, null))
			return -1;

		if (ewh.TestWaitOne(1000, sw))
			return -2;

		return TestPassed;
	}
 public void Ctor_StateModeNameCreatedNew_Windows(bool initialState, EventResetMode mode)
 {
     string name = Guid.NewGuid().ToString("N");
     bool createdNew;
     using (var ewh = new EventWaitHandle(false, EventResetMode.AutoReset, name, out createdNew))
     {
         Assert.True(createdNew);
         using (new EventWaitHandle(false, EventResetMode.AutoReset, name, out createdNew))
         {
             Assert.False(createdNew);
         }
     }
 }
 public void Set_Reset()
 {
     foreach (var iteration in Benchmark.Iterations)
     {
         using (EventWaitHandle are = new EventWaitHandle(false, EventResetMode.AutoReset))
         using (iteration.StartMeasurement())
         {
             are.Set(); are.Reset(); are.Set(); are.Reset();
             are.Set(); are.Reset(); are.Set(); are.Reset();
             are.Set(); are.Reset(); are.Set(); are.Reset();
             are.Set(); are.Reset(); are.Set(); are.Reset();
         }
     }
 }
    public void Ctor()
    {
        using (EventWaitHandle are = new EventWaitHandle(false, EventResetMode.AutoReset))
            Assert.False(are.WaitOne(0));
        using (EventWaitHandle are = new EventWaitHandle(true, EventResetMode.AutoReset))
            Assert.True(are.WaitOne(0));
        using (EventWaitHandle mre = new EventWaitHandle(false, EventResetMode.ManualReset))
            Assert.False(mre.WaitOne(0));
        using (EventWaitHandle mre = new EventWaitHandle(true, EventResetMode.ManualReset))
            Assert.True(mre.WaitOne(0));

        Assert.Throws<ArgumentException>(() => new EventWaitHandle(true, (EventResetMode)12345));
        Assert.Throws<ArgumentException>(() => new EventWaitHandle(true, EventResetMode.AutoReset, new string('a', 1000)));

        const string Name = "EventWaitHandleTestCtor";

        using (EventWaitHandle are = new EventWaitHandle(false, EventResetMode.AutoReset, Name))
            Assert.False(are.WaitOne(0));
        using (EventWaitHandle are = new EventWaitHandle(true, EventResetMode.AutoReset, Name))
            Assert.True(are.WaitOne(0));
        using (EventWaitHandle mre = new EventWaitHandle(false, EventResetMode.ManualReset, Name))
            Assert.False(mre.WaitOne(0));
        using (EventWaitHandle mre = new EventWaitHandle(true, EventResetMode.ManualReset, Name))
            Assert.True(mre.WaitOne(0));
        
        bool createdNew;
        using (EventWaitHandle are = new EventWaitHandle(false, EventResetMode.AutoReset, Name, out createdNew))
        {
            Assert.True(createdNew);
            using (EventWaitHandle are2 = new EventWaitHandle(false, EventResetMode.AutoReset, Name, out createdNew))
            {
                Assert.False(createdNew);
            }
        }
        using (EventWaitHandle mre = new EventWaitHandle(false, EventResetMode.ManualReset, Name, out createdNew))
        {
            Assert.True(createdNew);
            using (EventWaitHandle mre2 = new EventWaitHandle(false, EventResetMode.ManualReset, Name, out createdNew))
            {
                Assert.False(createdNew);
            }
        }

        using (Mutex m = new Mutex(false, Name))
        {
            Assert.Throws<WaitHandleCannotBeOpenedException>(() => new EventWaitHandle(false, EventResetMode.AutoReset, Name));
            Assert.Throws<WaitHandleCannotBeOpenedException>(() => new EventWaitHandle(false, EventResetMode.ManualReset, Name));
        }
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        this.cancelEvent = this.OpenEvent();
        this.settings = BXIBlockImportXmlSettings.Load();
        if (this.settings == null)
        {
            this.settings = new BXIBlockImportXmlSettings();
        }

        var siteTypes = TypeCB.Items;
        siteTypes.Clear();
        siteTypes.Add(new ListItem(GetMessageRaw("Combo.SelectIBlockType"), string.Empty));
        foreach (var type in this.helper.AllTypes)
        {
            siteTypes.Add(new ListItem(this.helper.GetTypeName(type), type.Id.ToString()));
        }

        var siteSites = SitesList.Items;
        siteSites.Clear();
        foreach (var site in this.helper.AllSites)
        {
            siteSites.Add(new ListItem(site.Name, site.Id));
        }

        if (siteSites.Count > 0)
        {
            siteSites[0].Selected = true;
        }

        this.CreatePreviewImage.Checked = this.settings.CreatePreviewImage;
        this.PreviewImageWidth.Text = this.settings.PreviewImageWidth.ToString();
        this.PreviewImageHeight.Text = this.settings.PreviewImageHeight.ToString();
        this.ResizeDetailImage.Checked = this.settings.ResizeDetailImage;
        this.DetailImageWidth.Text = this.settings.DetailImageWidth.ToString();
        this.DetailImageHeight.Text = this.settings.DetailImageHeight.ToString();
        this.ElementActions.SelectedIndex = (int)this.settings.ElementOmission;
        this.SectionActions.SelectedIndex = (int)this.settings.SectionOmission;
        this.SourceFile.Text = this.settings.SourceFile;

        this.UpdateControls();
    }
	public static int Run()
	{
		var sw = new Stopwatch();
		var ewh = new EventWaitHandle(false, System.Threading.EventResetMode.AutoReset);

		// Should not signal
		if (ewh.TestWaitOne(1000, sw))
			return -1;

		// Should signal
		ewh.Set();
		if (!ewh.TestWaitOne(0, null))
			return -2;

		// Should not signal
		if (ewh.TestWaitOne(1000, sw))
			return -3;
		
		return TestPassed;
	}
Exemple #11
0
    private int Run()
    {
        // Testing the initialState = false for a ManualResetEvent
        ewh = new EventWaitHandle(false, EventResetMode.ManualReset);

        Thread t = new Thread(new ThreadStart(ThreadWorker));
        t.Start();
        t.Join();

        ewh.Set();
        // when doing another wait, it should return immediately
        bool b = ewh.WaitOne(5000);//, false);
        if(b)
            iRet += 50;
        else
            Console.WriteLine("WaitOne() timed out");

        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }
	public static int Run()
	{
		var ewh = new EventWaitHandle(true, EventResetMode.ManualReset);

		// Should signal
		if (!ewh.TestWaitOne(0, null))
			return -1;

		// Should not signal
		ewh.Reset();
		if (ewh.TestWaitOne(1000, null))
			return -2;

		// Should signal
		ewh.Set();
		if (!ewh.TestWaitOne(0, null))
			return -3;

		return TestPassed;		
	}
Exemple #13
0
    private int Run()
    {
        // Testing the initialState = true for an AutoResetEvent
        int iRet = -1;
        ewh = (EventWaitHandle)new AutoResetEvent(true);

        Thread t = new Thread(new ThreadStart(ThreadWorker));
        t.Start();
        t.Join();

        // when doing another wait, it should not return until set.
        Console.WriteLine("Main: Waiting...");
        bool b = ewh.WaitOne(5000);//, false);
        if(b)
            Console.WriteLine("WaitOne didn't reset!");
        else
            iRet = 100;

        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }
	public static int Run()
	{
		var sw = new Stopwatch();		
		var ewh = new EventWaitHandle(false, EventResetMode.ManualReset);

		// Should not signal
		if (ewh.TestWaitOne(1000, sw))
			return -1;

		// Should signal
		ewh.Set();
		if (!ewh.TestWaitOne(0, sw))
			return -2;

		// Should not signal
		ewh.Reset();
		if (ewh.TestWaitOne(1000, sw))
			return -3;

		return TestPassed;
	}
Exemple #15
0
    private int Run()
    {
        // Testing the initialState = true for a ManualResetEvent
        int iRet = -1;
        ewh = new EventWaitHandle(true, EventResetMode.ManualReset);

        Thread t = new Thread(new ThreadStart(ThreadWorker));
        t.Start();
        t.Join();

        // This should return immediately
        ewh.WaitOne();
        ewh.Reset();

        // when doing another wait, it should not return until set.
        bool b = ewh.WaitOne(5000);//, false);
        if(b)
            Console.WriteLine("Event didn't reset!");
        else
            iRet = 100;

        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }
Exemple #16
0
 /// <summary>
 /// Turns this panel into multi-threaded mode.
 /// This will sort of glitch out other gdi things on the system, but at least its fast...
 /// </summary>
 public void ActivateThreaded()
 {
     ewh = new EventWaitHandle(false, EventResetMode.AutoReset);
     threadPaint = new Thread(PaintProc);
     threadPaint.Start();
 }
    public void OpenExisting()
    {
        const string Name = "EventWaitHandleTestOpenExisting";

        EventWaitHandle resultHandle;
        Assert.False(EventWaitHandle.TryOpenExisting(Name, out resultHandle));
        Assert.Null(resultHandle);

        using (EventWaitHandle are1 = new EventWaitHandle(false, EventResetMode.AutoReset, Name))
        {
            using (EventWaitHandle are2 = EventWaitHandle.OpenExisting(Name))
            {
                are1.Set();
                Assert.True(are2.WaitOne(0));
                Assert.False(are1.WaitOne(0));
                Assert.False(are2.WaitOne(0));

                are2.Set();
                Assert.True(are1.WaitOne(0));
                Assert.False(are2.WaitOne(0));
                Assert.False(are1.WaitOne(0));
            }

            Assert.True(EventWaitHandle.TryOpenExisting(Name, out resultHandle));
            Assert.NotNull(resultHandle);
            resultHandle.Dispose();
        }
    }
Exemple #18
0
	static void GetRequestStreamAsync (Uri uri, int i, EventWaitHandle complete)
	{
		byte [] data = new byte [32];
		HttpWebRequest request = (HttpWebRequest) WebRequest.Create (uri);
		request.Method = "POST";
		request.ContentLength = data.Length;

		RegisteredWaitHandle handle = null;

		BeginGetRequestStreamWithTimeout (request,
			(r1) =>
			{
				try {
					EndGetRequestStreamWithTimeout (request, r1, handle);
					SignalError (5);
					request.Abort ();
				} catch (WebException ex) {
					if (ex.Status != WebExceptionStatus.Timeout) {
						Console.WriteLine ("[{0}] {1}", i, ex.Status);
						SignalError (6);
					}
				}

				complete.Set ();
			},
			null,
			out handle);
	}
    /// <summary>
    /// Waits on 'waitEvent' with a timeout of 'millisceondsTimeout.  
    /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine.
    /// </summary>
    private void WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
    {
        Debug.Assert(MyLockHeld);

        waitEvent.Reset();
        numWaiters++;

        bool waitSuccessful = false;
        ExitMyLock();      // Do the wait outside of any lock 
        try
        {
            if (!waitEvent.WaitOne(millisecondsTimeout))
                throw new Exception("ReaderWriterLock timeout expired");
            waitSuccessful = true;
        }
        finally
        {
            EnterMyLock();
            --numWaiters;
            if (!waitSuccessful)        // We are going to throw for some reason.  Exit myLock. 
                ExitMyLock();
        }
    }
Exemple #20
0
 public EventHubEndToEndTests()
 {
     _results   = new List <string>();
     _testId    = Guid.NewGuid().ToString();
     _eventWait = new ManualResetEvent(initialState: false);
 }
Exemple #21
0
 static void Main(string[] args)
 {
     HomePath.SetHomeDirFullName(AppDomain.CurrentDomain.BaseDirectory);
     SetOut(new ConsoleOut());
     if (args.Length != 0)
     {
         if (args.Contains("--sha1"))
         {
             File.WriteAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sha1"), Sha1);
             return;
         }
     }
     try {
         SystemEvents.SessionEnding += SessionEndingEventHandler;
         StartTimer();
         _waitHandle = new AutoResetEvent(false);
         bool mutexCreated;
         try {
             _sMutexApp = new Mutex(true, "NTMinerDaemonAppMutex", out mutexCreated);
         }
         catch {
             mutexCreated = false;
         }
         if (mutexCreated)
         {
             if (!DevMode.IsDevMode)
             {
                 Write.Disable();
             }
             NTMinerRegistry.SetDaemonVersion(Sha1);
             NTMinerRegistry.SetAutoBoot("NTMinerDaemon", true);
             #region 是否自动启动挖矿端
             bool isAutoBoot = MinerProfileUtil.GetIsAutoBoot();
             if (isAutoBoot)
             {
                 string location = NTMinerRegistry.GetLocation(NTMinerAppType.MinerClient);
                 if (!string.IsNullOrEmpty(location) && File.Exists(location))
                 {
                     string    processName = Path.GetFileName(location);
                     Process[] processes   = Process.GetProcessesByName(processName);
                     if (processes.Length == 0)
                     {
                         string arguments = NTMinerRegistry.GetArguments(NTMinerAppType.MinerClient);
                         if (NTMinerRegistry.GetIsLastIsWork())
                         {
                             arguments = "--work " + arguments;
                         }
                         try {
                             Process.Start(location, arguments);
                             Write.DevOk(() => $"启动挖矿端 {location} {arguments}");
                         }
                         catch (Exception e) {
                             Logger.ErrorDebugLine($"启动挖矿端失败因为异常 {location} {arguments}", e);
                         }
                     }
                     else
                     {
                         Write.DevDebug($"挖矿端已经在运行中无需启动");
                     }
                 }
             }
             #endregion
             Run();
         }
     }
     catch (Exception e) {
         Logger.ErrorDebugLine(e);
     }
 }
Exemple #22
0
 /// <summary>
 /// Try to get the ready handle for the given scenario.
 /// </summary>
 /// <exception cref="CacheException"/>
 public static bool TryOpenExistingReadyWaitHandle(string scenario, out EventWaitHandle readyEvent)
 {
     return(TryOpenExistingReadyWaitHandle(scenario, out readyEvent, 0));
 }
Exemple #23
0
        public static void Main(string[] args)
        {
            if (!Mutex.TryOpenExisting(MutexName, out _))
            {
                using (new Mutex(false, MutexName))
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);

                    JsonConvert.DefaultSettings = () =>
                    {
                        var settings = new JsonSerializerSettings
                        {
                            ContractResolver = new CamelCasePropertyNamesContractResolver(),
                        };
                        settings.Converters.Add(new StringEnumConverter(typeof(CamelCaseNamingStrategy)));

                        return(settings);
                    };

                    var applicationDataContainers = new ApplicationDataContainers
                    {
                        LocalSettings   = new ApplicationDataContainerAdapter(ApplicationData.Current.LocalSettings),
                        RoamingSettings = new ApplicationDataContainerAdapter(ApplicationData.Current.RoamingSettings),
                        KeyBindings     = new ApplicationDataContainerAdapter(ApplicationData.Current.RoamingSettings.CreateContainer(Constants.KeyBindingsContainerName, ApplicationDataCreateDisposition.Always)),
                        ShellProfiles   = new ApplicationDataContainerAdapter(ApplicationData.Current.LocalSettings.CreateContainer(Constants.ShellProfilesContainerName, ApplicationDataCreateDisposition.Always)),
                        Themes          = new ApplicationDataContainerAdapter(ApplicationData.Current.RoamingSettings.CreateContainer(Constants.ThemesContainerName, ApplicationDataCreateDisposition.Always))
                    };

                    var containerBuilder = new ContainerBuilder();

                    containerBuilder.RegisterInstance(applicationDataContainers);
                    containerBuilder.RegisterType <NotificationService>().As <INotificationService>().InstancePerDependency();
                    containerBuilder.RegisterType <TerminalsManager>().SingleInstance();
                    containerBuilder.RegisterType <ToggleWindowService>().SingleInstance();
                    containerBuilder.RegisterInstance(new HotKeyManager()).SingleInstance();
                    containerBuilder.RegisterType <SystemTrayApplicationContext>().SingleInstance();
                    containerBuilder.RegisterType <AppCommunicationService>().SingleInstance();
                    containerBuilder.RegisterType <DefaultValueProvider>().As <IDefaultValueProvider>();
                    containerBuilder.RegisterType <SettingsService>().As <ISettingsService>().SingleInstance();
                    containerBuilder.RegisterType <UpdateService>().As <IUpdateService>().SingleInstance();
                    containerBuilder.RegisterInstance(Dispatcher.CurrentDispatcher).SingleInstance();

                    var container = containerBuilder.Build();

                    // TODO: It's maybe better to wait for logging to be configured before continuing?
                    // ReSharper disable once AssignmentIsFullyDiscarded
                    _ = ConfigureLoggingAsync();

                    var appCommunicationService = container.Resolve <AppCommunicationService>();

                    if (args.Length > 0 && args[2] == "appLaunched")
                    {
                        // ReSharper disable once AssignmentIsFullyDiscarded
                        _ = appCommunicationService.StartAppServiceConnectionAsync();
                    }

#if !STORE
                    // ReSharper disable once AssignmentIsFullyDiscarded
                    _ = Task.Factory.StartNew(() => container.Resolve <IUpdateService>().CheckForUpdateAsync());
#endif
                    var settingsService = container.Resolve <ISettingsService>();

                    // ReSharper disable once AssignmentIsFullyDiscarded
                    _ = Task.Factory.StartNew(() => Utilities.MuteTerminal(settingsService.GetApplicationSettings().MuteTerminalBeeps));

                    if (settingsService.GetApplicationSettings().EnableTrayIcon)
                    {
                        Application.Run(container.Resolve <SystemTrayApplicationContext>());
                    }
                    else
                    {
                        Application.Run();
                    }
                }
            }
            else
            {
                var eventWaitHandle = EventWaitHandle.OpenExisting(AppCommunicationService.EventWaitHandleName, System.Security.AccessControl.EventWaitHandleRights.Modify);
                eventWaitHandle.Set();
            }
        }
        private EventWaitHandle EventInitialisation(string eventName)
        {
            EventWaitHandle ewh;

            try
            {
                ewh = EventWaitHandle.OpenExisting(eventName);
            }
            catch (WaitHandleCannotBeOpenedException)
            {
                string user = Environment.UserDomainName + "\\"
                              + Environment.UserName;
                EventWaitHandleSecurity ewhSec =
                    new EventWaitHandleSecurity();

                EventWaitHandleAccessRule rule =
                    new EventWaitHandleAccessRule(user,
                                                  EventWaitHandleRights.Synchronize |
                                                  EventWaitHandleRights.Modify,
                                                  AccessControlType.Deny);
                ewhSec.AddAccessRule(rule);

                rule = new EventWaitHandleAccessRule(user,
                                                     EventWaitHandleRights.ReadPermissions |
                                                     EventWaitHandleRights.ChangePermissions,
                                                     AccessControlType.Allow);
                ewhSec.AddAccessRule(rule);

                ewh = new EventWaitHandle(true,
                                          EventResetMode.AutoReset,
                                          eventName,
                                          out bool wasCreated,
                                          ewhSec);
            }
            catch (UnauthorizedAccessException)
            {
                ewh = EventWaitHandle.OpenExisting(eventName,
                                                   EventWaitHandleRights.ReadPermissions |
                                                   EventWaitHandleRights.ChangePermissions);

                EventWaitHandleSecurity ewhSec = ewh.GetAccessControl();

                string user = Environment.UserDomainName + "\\"
                              + Environment.UserName;

                EventWaitHandleAccessRule rule =
                    new EventWaitHandleAccessRule(user,
                                                  EventWaitHandleRights.Synchronize |
                                                  EventWaitHandleRights.Modify,
                                                  AccessControlType.Deny);

                ewhSec.RemoveAccessRule(rule);

                rule = new EventWaitHandleAccessRule(user,
                                                     EventWaitHandleRights.Synchronize |
                                                     EventWaitHandleRights.Modify,
                                                     AccessControlType.Allow);

                ewhSec.AddAccessRule(rule);

                ewh.SetAccessControl(ewhSec);

                ewh = EventWaitHandle.OpenExisting(eventName);
            }

            return(ewh);
        }
Exemple #25
0
        static void Main(string[] args)
        {
#if DotNetStandard
            Console.WriteLine("WARN : Linux .NET Core not support name EventWaitHandle");
#else
            bool            createdProcessWait;
            EventWaitHandle processWait = new EventWaitHandle(false, EventResetMode.ManualReset, "AutoCSer.TestCase.ChatServer", out createdProcessWait);
            if (createdProcessWait)
            {
                using (processWait)
                {
#endif
            Console.WriteLine(@"http://www.AutoCSer.com/TcpServer/MethodServer.html
");
#if !NoAutoCSer
            using (Server.TcpOpenServer server = new Server.TcpOpenServer())
            {
                if (server.IsListen)
                {
#if DotNetStandard
#if DEBUG
                    FileInfo clientFile = new FileInfo(Path.Combine(AutoCSer.PubPath.ApplicationPath, @"..\..\..\..\ChatClient\bin\Debug\netcoreapp2.0\AutoCSer.TestCase.ChatClient.dll".pathSeparator()));
#else
                    FileInfo clientFile = new FileInfo(Path.Combine(AutoCSer.PubPath.ApplicationPath, @"..\..\..\..\ChatClient\bin\Release\netcoreapp2.0\AutoCSer.TestCase.ChatClient.dll".pathSeparator()));
#endif
                    if (!clientFile.Exists)
                    {
                        clientFile = new FileInfo(Path.Combine(AutoCSer.PubPath.ApplicationPath, @"AutoCSer.TestCase.ChatClient.dll"));
                    }
                    if (clientFile.Exists)
                    {
                        ProcessStartInfo process = new ProcessStartInfo("dotnet", clientFile.FullName + " user1");
                        process.UseShellExecute = true;
                        Process.Start(process);
                        process.Arguments = clientFile.FullName + " user2";
                        Process.Start(process);
                        process.Arguments = clientFile.FullName + " user3";
                        Process.Start(process);
                        process.Arguments = clientFile.FullName + " user4";
                        Process.Start(process);
                    }
#else
#if DEBUG
                    FileInfo clientFile = new FileInfo(Path.Combine(AutoCSer.PubPath.ApplicationPath, @"..\..\..\ChatClient\bin\Debug\AutoCSer.TestCase.ChatClient.exe".pathSeparator()));
#else
                    FileInfo clientFile = new FileInfo(Path.Combine(AutoCSer.PubPath.ApplicationPath, @"..\..\..\ChatClient\bin\Release\AutoCSer.TestCase.ChatClient.exe".pathSeparator()));
#endif
                    if (!clientFile.Exists)
                    {
                        clientFile = new FileInfo(Path.Combine(AutoCSer.PubPath.ApplicationPath, @"AutoCSer.TestCase.ChatClient.exe"));
                    }
                    if (clientFile.Exists)
                    {
                        Process.Start(clientFile.FullName, "user1");
                        Process.Start(clientFile.FullName, "user2");
                        Process.Start(clientFile.FullName, "user3");
                        Process.Start(clientFile.FullName, "user4");
                    }
#endif
                    else
                    {
                        Console.WriteLine("未找到 群聊 客户端程序");
                    }
                    Console.WriteLine("Press quit to exit.");
                    while (Console.ReadLine() != "quit")
                    {
                        ;
                    }
                }
                else
                {
                    Console.WriteLine("群聊服务 启动失败");
                    Console.ReadKey();
                }
            }
#endif
#if !DotNetStandard
        }
    }
#endif
        }
Exemple #26
0
        public void TestSessionJoined()
        {
            AllJoyn.QStatus status = AllJoyn.QStatus.FAIL;

            // create+start+connect bus attachment
            AllJoyn.BusAttachment servicebus = null;
            servicebus = new AllJoyn.BusAttachment("SessionTestService", true);
            Assert.NotNull(servicebus);

            status = servicebus.Start();
            Assert.Equal(AllJoyn.QStatus.OK, status);

            status = servicebus.Connect(AllJoynTestCommon.GetConnectSpec());
            Assert.Equal(AllJoyn.QStatus.OK, status);

            // Create session
            AllJoyn.SessionOpts opts = new AllJoyn.SessionOpts(
                AllJoyn.SessionOpts.TrafficType.Messages, false,
                AllJoyn.SessionOpts.ProximityType.Any, AllJoyn.TransportMask.Any);
            ushort sessionPort = SERVICE_PORT;

            // create the session port listener
            AllJoyn.SessionPortListener sessionPortListener = new TestSessionPortListener(this);

            // bind to the session port
            status = servicebus.BindSessionPort(ref sessionPort, opts, sessionPortListener);
            Assert.Equal(AllJoyn.QStatus.OK, status);

            // request name
            status = servicebus.RequestName(OBJECT_NAME, AllJoyn.DBus.NameFlags.ReplaceExisting | AllJoyn.DBus.NameFlags.DoNotQueue);
            Assert.Equal(AllJoyn.QStatus.OK, status);

            // Advertise name
            status = servicebus.AdvertiseName(OBJECT_NAME, opts.Transports);
            Assert.Equal(AllJoyn.QStatus.OK, status);

            ///////////////////////////////////////////////////////////
            foundAdvertisedNameFlag = false;
            acceptSessionJoinerFlag = false;
            sessionJoinedFlag       = false;

            // try to join the session & verify callbacks are called
            AllJoyn.BusAttachment bus = null;
            bus = new AllJoyn.BusAttachment("SessionTest", true);
            Assert.NotNull(bus);

            status = bus.Start();
            Assert.Equal(AllJoyn.QStatus.OK, status);

            status = bus.Connect(AllJoynTestCommon.GetConnectSpec());
            Assert.Equal(AllJoyn.QStatus.OK, status);

            // register the bus listener
            AllJoyn.BusListener busListener = new TestBusListener(this);
            bus.RegisterBusListener(busListener);

            // find the advertised name from the "servicebus"
            status = bus.FindAdvertisedName(OBJECT_NAME);
            Assert.Equal(AllJoyn.QStatus.OK, status);
            EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "FoundAdvertisedName");

            ewh.WaitOne(MaxWaitTime);
            Assert.Equal(true, foundAdvertisedNameFlag);

            // try to join & verify that the sessionedJoined callback was called
            uint sSessionId;

            status = bus.JoinSession(OBJECT_NAME, SERVICE_PORT, null, out sSessionId, opts);
            Assert.Equal(AllJoyn.QStatus.OK, status);
            ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "SessionJoined");
            ewh.WaitOne(MaxWaitTime);
            Assert.Equal(true, acceptSessionJoinerFlag);
            Assert.Equal(true, sessionJoinedFlag);
            servicebus.ReleaseName(OBJECT_NAME);
            servicebus.Dispose();
            bus.Dispose();
        }
Exemple #27
0
        public void RemoveSessionMember()
        {
            AllJoyn.QStatus status = AllJoyn.QStatus.FAIL;

            ///////////////////////////////////////////////////////////
            // Setup the session host
            ///////////////////////////////////////////////////////////
            SetupHost();
            // Create session
            AllJoyn.SessionOpts opts = new AllJoyn.SessionOpts(
                AllJoyn.SessionOpts.TrafficType.Messages, true,
                AllJoyn.SessionOpts.ProximityType.Any, AllJoyn.TransportMask.Any);
            ushort sessionPort = SERVICE_PORT;

            // create the session port listener
            AllJoyn.SessionPortListener sessionPortListener = new TestSessionPortListener(this);

            // bind to the session port
            status = hostBus.BindSessionPort(ref sessionPort, opts, sessionPortListener);
            Assert.Equal(AllJoyn.QStatus.OK, status);

            // request name
            status = hostBus.RequestName(OBJECT_NAME, AllJoyn.DBus.NameFlags.ReplaceExisting | AllJoyn.DBus.NameFlags.DoNotQueue);
            Assert.Equal(AllJoyn.QStatus.OK, status);

            // Advertise name
            status = hostBus.AdvertiseName(OBJECT_NAME, opts.Transports);
            Assert.Equal(AllJoyn.QStatus.OK, status);

            ///////////////////////////////////////////////////////////
            // Setup session member one
            ///////////////////////////////////////////////////////////
            SetupMemberOne();
            // register sessionMemberOne's bus listener
            AllJoyn.BusListener busListenerMemberOne = new TestBusListener(this);
            memberOneBus.RegisterBusListener(busListenerMemberOne);
            // create the session listener
            AllJoyn.SessionListener sessionListener = new TestSessionListener2(this);

            ///////////////////////////////////////////////////////////
            // have sessionMemberOne find and join the session
            foundAdvertisedNameFlag = false;
            status = memberOneBus.FindAdvertisedName(OBJECT_NAME);              // find the advertised name from the "hostbus"
            Assert.Equal(AllJoyn.QStatus.OK, status);
            EventWaitHandle ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "FoundAdvertisedName");

            ewh.WaitOne(MaxWaitTime);
            Assert.Equal(true, foundAdvertisedNameFlag);

            uint sSessionId;

            acceptSessionJoinerFlag = false;
            sessionJoinedFlag       = false;
            status = memberOneBus.JoinSession(OBJECT_NAME, SERVICE_PORT, sessionListener, out sSessionId, opts);
            Assert.Equal(AllJoyn.QStatus.OK, status);
            ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "SessionJoined");
            ewh.WaitOne(MaxWaitTime);

            // verify that sessionMemberOne joined by checking that the sessionedJoined callback was called
            Assert.Equal(true, acceptSessionJoinerFlag);
            Assert.Equal(true, sessionJoinedFlag);

            ///////////////////////////////////////////////////////////
            // Now have the host leave & verify SessionLost callback is triggered
            sessionLostReasonFlag    = false;
            reasonMarker             = AllJoyn.SessionListener.SessionLostReason.ALLJOYN_SESSIONLOST_INVALID;
            sessionMemberRemovedFlag = false;
            hostBus.RemoveSessionMember(sSessionId, memberOneBus.UniqueName);
            ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "SessionLostReason");
            ewh.WaitOne(MaxWaitTime);
            Assert.Equal(true, sessionLostReasonFlag);
            Assert.Equal(AllJoyn.SessionListener.SessionLostReason.ALLJOYN_SESSIONLOST_REMOVED_BY_BINDER, reasonMarker);

            // SessionMemberRemoved should also be triggered
            ewh = new EventWaitHandle(false, EventResetMode.AutoReset, "SessionMemberRemoved");
            ewh.WaitOne(MaxWaitTime);
            Assert.Equal(true, sessionMemberRemovedFlag);
            hostBus.Stop();
            hostBus.Join();
            hostBus.ReleaseName(OBJECT_NAME);

            memberOneBus.Stop();
            memberOneBus.Join();

            memberOneBus.Dispose();
            hostBus.Dispose();
        }
        /// <summary>
        /// Initialize for playing the specified wave stream
        /// </summary>
        /// <param name="waveProvider">IWaveProvider to play</param>
        public void Init(IWaveProvider waveProvider)
        {
            long latencyRefTimes = latencyMilliseconds * 10000;

            outputFormat = waveProvider.WaveFormat;
            // first attempt uses the WaveFormat from the WaveStream
            WaveFormatExtensible closestSampleRateFormat;

            if (!audioClient.IsFormatSupported(shareMode, outputFormat, out closestSampleRateFormat))
            {
                // Use closesSampleRateFormat (in sharedMode, it equals usualy to the audioClient.MixFormat)
                // See documentation : http://msdn.microsoft.com/en-us/library/ms678737(VS.85).aspx
                // They say : "In shared mode, the audio engine always supports the mix format"
                // The MixFormat is more likely to be a WaveFormatExtensible.
                if (closestSampleRateFormat == null)
                {
                    outputFormat = GetFallbackFormat();
                }
                else
                {
                    outputFormat = closestSampleRateFormat;
                }

                try
                {
                    // just check that we can make it.
                    using (new ResamplerDmoStream(waveProvider, outputFormat))
                    {
                    }
                }
                catch (Exception)
                {
                    // On Windows 10 some poorly coded drivers return a bad format in to closestSampleRateFormat
                    // In that case, try and fallback as if it provided no closest (e.g. force trying the mix format)
                    outputFormat = GetFallbackFormat();
                    using (new ResamplerDmoStream(waveProvider, outputFormat))
                    {
                    }
                }
                dmoResamplerNeeded = true;
            }
            else
            {
                dmoResamplerNeeded = false;
            }
            sourceProvider = waveProvider;

            // If using EventSync, setup is specific with shareMode
            if (isUsingEventSync)
            {
                // Init Shared or Exclusive
                if (shareMode == AudioClientShareMode.Shared)
                {
                    // With EventCallBack and Shared, both latencies must be set to 0 (update - not sure this is true anymore)
                    //
                    audioClient.Initialize(shareMode, AudioClientStreamFlags.EventCallback, latencyRefTimes, 0,
                                           outputFormat, Guid.Empty);

                    // Windows 10 returns 0 from stream latency, resulting in maxing out CPU usage later
                    var streamLatency = audioClient.StreamLatency;
                    if (streamLatency != 0)
                    {
                        // Get back the effective latency from AudioClient
                        latencyMilliseconds = (int)(streamLatency / 10000);
                    }
                }
                else
                {
                    try
                    {
                        // With EventCallBack and Exclusive, both latencies must equals
                        audioClient.Initialize(shareMode, AudioClientStreamFlags.EventCallback, latencyRefTimes, latencyRefTimes,
                                               outputFormat, Guid.Empty);
                    }
                    catch (COMException ex)
                    {
                        // Starting with Windows 7, Initialize can return AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED for a render device.
                        // We should to initialize again.
                        if (ex.ErrorCode != ErrorCodes.AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED)
                        {
                            throw ex;
                        }

                        // Calculate the new latency.
                        long newLatencyRefTimes = (long)(10000000.0 /
                                                         (double)this.outputFormat.SampleRate *
                                                         (double)this.audioClient.BufferSize + 0.5);

                        this.audioClient.Dispose();
                        this.audioClient = this.mmDevice.AudioClient;
                        this.audioClient.Initialize(this.shareMode, AudioClientStreamFlags.EventCallback,
                                                    newLatencyRefTimes, newLatencyRefTimes, this.outputFormat, Guid.Empty);
                    }
                }

                // Create the Wait Event Handle
                frameEventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
                audioClient.SetEventHandle(frameEventWaitHandle.SafeWaitHandle.DangerousGetHandle());
            }
            else
            {
                // Normal setup for both sharedMode
                audioClient.Initialize(shareMode, AudioClientStreamFlags.None, latencyRefTimes, 0,
                                       outputFormat, Guid.Empty);
            }

            // Get the RenderClient
            renderClient = audioClient.AudioRenderClient;
        }
 public RequestHandler(Func <string> request)
 {
     _handle = new EventWaitHandle(false, EventResetMode.ManualReset);
     Start(request);
 }
Exemple #30
0
 /// <summary>
 /// 客户端任务池
 /// </summary>
 /// <param name="maxClientCount">最大实例数量</param>
 /// <param name="isKeepAlive">保持连接最大次数</param>
 public Task(int maxClientCount, int keepAliveCount)
 {
     clients        = new clientType[maxClientCount];
     KeepAliveCount = keepAliveCount;
     freeWait       = new EventWaitHandle(true, EventResetMode.ManualReset);
 }
 // Methods
 public void Dispose()
 {
     lock (m_interlock)
     {
         m_disposing = true;
         if (Enabled)
         {
             Enabled = false;
         }
         if (m_quitHandle != null)
         {
             m_quitHandle.Set();
             m_quitHandle.Close();
             m_quitHandle = null;
         }
     }
 }
Exemple #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="IpInfoUpdater"/> class.
 /// </summary>
 public IpInfoUpdater()
 {
     forcedUpdateHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
 }
Exemple #33
0
        static void InnerMain(Mutex InstanceMutex, EventWaitHandle ActivateEvent, string[] Args)
        {
            List <string> RemainingArgs = new List <string>(Args);

            string UpdatePath;

            ParseArgument(RemainingArgs, "-updatepath=", out UpdatePath);

            string UpdateSpawn;

            ParseArgument(RemainingArgs, "-updatespawn=", out UpdateSpawn);

            bool bRestoreState;

            ParseOption(RemainingArgs, "-restorestate", out bRestoreState);

            bool bUnstable;

            ParseOption(RemainingArgs, "-unstable", out bUnstable);

            string ProjectFileName;

            ParseArgument(RemainingArgs, "-project=", out ProjectFileName);

            string UpdateConfigFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "AutoUpdate.ini");

            MergeUpdateSettings(UpdateConfigFile, ref UpdatePath, ref UpdateSpawn);

            string SyncVersionFile = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "SyncVersion.txt");

            if (File.Exists(SyncVersionFile))
            {
                try
                {
                    SyncVersion = File.ReadAllText(SyncVersionFile).Trim();
                }
                catch (Exception)
                {
                    SyncVersion = null;
                }
            }

            string DataFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "UnrealGameSync");

            Directory.CreateDirectory(DataFolder);

            using (TelemetryWriter Telemetry = new TelemetryWriter(SqlConnectionString, Path.Combine(DataFolder, "Telemetry.log")))
            {
                try
                {
                    using (UpdateMonitor UpdateMonitor = new UpdateMonitor(new PerforceConnection(null, null, null), UpdatePath))
                    {
                        using (BoundedLogWriter 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());

                            UserSettings Settings = new UserSettings(Path.Combine(DataFolder, "UnrealGameSync.ini"));
                            if (!String.IsNullOrEmpty(ProjectFileName))
                            {
                                string FullProjectFileName = Path.GetFullPath(ProjectFileName);
                                if (!Settings.OpenProjectFileNames.Any(x => x.Equals(FullProjectFileName, StringComparison.InvariantCultureIgnoreCase)))
                                {
                                    Settings.OpenProjectFileNames = Settings.OpenProjectFileNames.Concat(new string[] { FullProjectFileName }).ToArray();
                                }
                            }

                            MainWindow Window = new MainWindow(UpdateMonitor, SqlConnectionString, DataFolder, ActivateEvent, bRestoreState, UpdateSpawn ?? Assembly.GetExecutingAssembly().Location, ProjectFileName, bUnstable, Log, Settings);
                            if (bUnstable)
                            {
                                Window.Text += String.Format(" (UNSTABLE BUILD {0})", Assembly.GetExecutingAssembly().GetName().Version);
                            }
                            Application.Run(Window);
                        }

                        if (UpdateMonitor.IsUpdateAvailable && UpdateSpawn != null)
                        {
                            InstanceMutex.Close();
                            Utility.SpawnProcess(UpdateSpawn, "-restorestate" + (bUnstable? " -unstable" : ""));
                        }
                    }
                }
                catch (Exception Ex)
                {
                    TelemetryWriter.Enqueue(TelemetryErrorType.Crash, Ex.ToString(), null, DateTime.Now);
                    MessageBox.Show(String.Format("UnrealGameSync has crashed.\n\n{0}", Ex.ToString()));
                }
            }
        }
    private void WaitOnEvent(EventWaitHandle waitEvent, ref uint numWaiters, int millisecondsTimeout)
    {
        waitEvent.Reset();
        numWaiters++;

        bool waitSuccessful = false;
        ExitMyLock();
        try {
            if (!waitEvent.WaitOne(millisecondsTimeout))
                throw new InvalidOperationException("ReaderWriterLock timeout expired");
            waitSuccessful = true;
        }
        finally {
            EnterMyLock();
            --numWaiters;
            if (!waitSuccessful)
                ExitMyLock();
        }
    }
Exemple #35
0
 public void OpenExisting_InvalidNames_Windows()
 {
     AssertExtensions.Throws <ArgumentNullException>("name", () => EventWaitHandle.OpenExisting(null));
     AssertExtensions.Throws <ArgumentException>("name", null, () => EventWaitHandle.OpenExisting(string.Empty));
 }
Exemple #36
0
 public static bool TryOpenExisting(string name, EventWaitHandleRights rights, out EventWaitHandle result);
Exemple #37
0
        public void Start(NetPeer knowPeer, string masterServerAdress, int masterServerPort, object caller)
        {
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            entitySystem = new UnityActor.ActorSystem("entitySystem")
            {
                Options = new UnityActor.ActorSystemOptions()
                {
                    MultipleSameIdAllowed  = false,
                    ThrowErrorOnExistingID = false, //: 1
                }
            };

            //: 1
            // Cela permettra d'avoir plusieurs entités d'un même groupe sans problème
            // Puis de toute façon, il n y aura pas de problèmes avec les joueurs :
            // Ils seront remplacé.

            gameServer = this;

            UsingPeer = knowPeer;

            UsingPeer.RegisterReceivedCallback(new SendOrPostCallback((o) =>
                                                                      { try { ReceiveIncomingMessage((NetPeer)o); } catch (Exception ex) { Console.WriteLine($"ERROR: {ex.Message}\n{ex.StackTrace}"); } }));

            UsingPeer.Start();

            var hailMessage = UsingPeer.CreateMessage("CONNECT");

            hailMessage.Write("GAMEROOM");


            UsingPeer.Connect(masterServerAdress, masterServerPort, hailMessage);

            //peer.Connect("127.0.0.1", 7641);
            Time.StartTime = TimeSpan.Zero;

            Time.Timer          = new System.Timers.Timer(10);
            Time.Timer.Elapsed += new System.Timers.ElapsedEventHandler((object obj, System.Timers.ElapsedEventArgs args) =>
            {
                Time.LastTime    = Time.TimeElapsed;
                Time.TickElapsed = args.SignalTime.Millisecond;
            });
            Time.Timer.Enabled = true;

            if (caller != null && caller.GetType() == typeof(MonoBehaviour))
            {
                caller.GetType().GetMethod("print").Invoke(this, new object[] { "started!" });
            }

            bool createdNew;
            var  waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, (Guid.NewGuid().ToString() + Guid.NewGuid().ToString()), out createdNew);
            var  signaled   = false;

            //var timer = new Timer(, null, TimeSpan.Zero, TimeSpan.FromSeconds(10));

            Console.Title = "Connecting";

            while (UsingPeer.Status != NetPeerStatus.Running)
            {
                ;
            }
            //Room.hasLoaded = true;

            /*Log($@"Room info:
             * Creator Name: {Room.creatorName}
             * Room Description: {Room.description}
             * Adress: {Room.ipAdress}:{Room.port}
             * ");*/

            /* var testMsg = UsingPeer.CreateMessage().Start(Constants.SYSTEM.DEBUG);
             * testMsg.Subscribe((netMsg) => Console.WriteLine("Seems like it worked, no?"));
             *
             * UsingPeer.SendUnconnectedToSelf(testMsg);*/

            Console.WriteLine("ke");

            timeLeft_BeforeShutdown = -1f;
            shutdownSent            = false;
            currentGameState        = EGameState.Basement;

            do
            {
                signaled = waitHandle.WaitOne(TimeSpan.FromSeconds(1f / FPS));
                Update();
            }while (!signaled && !stop);

            while (!shutdownSent)
            {
                ;
            }
        }
Exemple #38
0
 public void Ctor_StateMode(bool initialState, EventResetMode mode)
 {
     using (var ewh = new EventWaitHandle(initialState, mode))
         Assert.Equal(initialState, ewh.WaitOne(0));
 }
    public SyncEvents()
    {
        // AutoResetEvent is used for the "new item" event because
        // we want this event to reset automatically each time the
        // consumer thread responds to this event.
        _newItemEvent = new AutoResetEvent(false);

        // ManualResetEvent is used for the "exit" event because
        // we want multiple threads to respond when this event is
        // signaled. If we used AutoResetEvent instead, the event
        // object would revert to a non-signaled state with after
        // a single thread responded, and the other thread would
        // fail to terminate.
        _exitThreadEvent = new ManualResetEvent(false);

        // The two events are placed in a WaitHandle array as well so
        // that the consumer thread can block on both events using
        // the WaitAny method.
        _eventArray = new WaitHandle[2];
        _eventArray[0] = _newItemEvent;
        _eventArray[1] = _exitThreadEvent;
    }
Exemple #40
0
 public CustomDelegateCommand(Action <TParam> executeMethod, Func <TParam, bool> canExecuteMethod, Func <TParam, bool> validateMethod) : base(executeMethod, canExecuteMethod)
 {
     BackgroundTaskWaitHandle = new EventWaitHandle(true, EventResetMode.ManualReset);
     _validateMethod          = validateMethod;
 }
    /// <summary>
    /// A routine for lazily creating a event outside the lock (so if errors
    /// happen they are outside the lock and that we don't do much work
    /// while holding a spin lock).  If all goes well, reenter the lock and
    /// set 'waitEvent' 
    /// </summary>
    private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent) {
        Debug.Assert(MyLockHeld);
        Debug.Assert(waitEvent == null);

        ExitMyLock();
        EventWaitHandle newEvent;
        if (makeAutoResetEvent) 
            newEvent = new AutoResetEvent(false);
        else 
            newEvent = new ManualResetEvent(false);
        EnterMyLock();
        if (waitEvent == null)          // maybe someone snuck in. 
            waitEvent = newEvent;
    }
Exemple #42
0
 /// <summary>
 ///
 /// </summary>
 public void Dispose()
 {
     _waitHandle.Set();
     _waitHandle.Dispose();
     _waitHandle = null;
 }
Exemple #43
0
    public SyncEvents()
    {
        // AutoResetEvent 用于“新项”事件,因为
        // 我们希望每当使用者线程响应此事件时,
        // 此事件就会自动重置。
        _newItemEvent = new AutoResetEvent(false);

        // ManualResetEvent 用于“退出”事件,因为
        // 我们希望发出此事件的信号时有多个线程响应。
        // 如果使用 AutoResetEvent,事件
        // 对象将在单个线程作出响应之后恢复为
        // 未发信号的状态,而其他线程将
        // 无法终止。
        _exitThreadEvent = new ManualResetEvent(false);

        // 这两个事件也放在一个 WaitHandle 数组中,以便
        // 使用者线程可以使用 WaitAny 方法
        // 阻塞这两个事件。
        _eventArray = new WaitHandle[2];
        _eventArray[0] = _newItemEvent;
        _eventArray[1] = _exitThreadEvent;
    }
Exemple #44
0
        private static MouseNotOverManagedWaitHandle CreateAndShowMessage(UIElement snackbar,
                                                                          SnackbarMessageQueueItem messageQueueItem, EventWaitHandle actionClickWaitHandle)
        {
            var clickCount      = 0;
            var snackbarMessage = Create(messageQueueItem);

            snackbarMessage.ActionClick += (sender, args) =>
            {
                if (++clickCount == 1)
                {
                    DoActionCallback(messageQueueItem);
                }
                actionClickWaitHandle.Set();
            };
            snackbar.SetCurrentValue(Snackbar.MessageProperty, snackbarMessage);
            snackbar.SetCurrentValue(Snackbar.IsActiveProperty, true);
            return(new MouseNotOverManagedWaitHandle(snackbar));
        }
Exemple #45
0
 public Event(bool manualReset = false)
 {
     EventObj = new EventWaitHandle(false, (manualReset ? EventResetMode.ManualReset : EventResetMode.AutoReset));
 }
        ///////////////////////////////////////////////////////////////////////

        #region Program Entry Point
        /// <summary>
        /// This is the entry-point for this tool.  It handles processing the
        /// command line arguments, setting up the web client, downloading the
        /// file, and saving it to the file system.
        /// </summary>
        /// <param name="args">
        /// The command line arguments.
        /// </param>
        /// <returns>
        /// Zero upon success; non-zero on failure.  This will be one of the
        /// values from the <see cref="ExitCode" /> enumeration.
        /// </returns>
        private static int Main(
            string[] args
            )
        {
            //
            // NOTE: Sanity check the command line arguments.
            //
            if (args == null)
            {
                Error(null, true);
                return((int)ExitCode.MissingArgs);
            }

            if (args.Length != 1)
            {
                Error(null, true);
                return((int)ExitCode.WrongNumArgs);
            }

            //
            // NOTE: Attempt to convert the first (and only) command line
            //       argument to an absolute URI.
            //
            Uri uri;

            if (!Uri.TryCreate(args[0], UriKind.Absolute, out uri))
            {
                Error("Could not create absolute URI from argument.", false);
                return((int)ExitCode.BadUri);
            }

            //
            // NOTE: Attempt to extract the file name portion of the URI we
            //       just created.
            //
            string fileName = GetFileName(uri);

            if (fileName == null)
            {
                Error("Could not extract the file name from the URI.", false);
                return((int)ExitCode.BadFileName);
            }

            //
            // NOTE: Grab the temporary path setup for this process.  If it is
            //       unavailable, we will not continue.
            //
            string directory = Path.GetTempPath();

            if (String.IsNullOrEmpty(directory) ||
                !Directory.Exists(directory))
            {
                Error("Temporary directory is invalid or unavailable.", false);
                return((int)ExitCode.BadTempPath);
            }

            try
            {
                using (WebClient webClient = new WebClient())
                {
                    //
                    // NOTE: Create the event used to signal completion of the
                    //       file download.
                    //
                    doneEvent = new ManualResetEvent(false);

                    //
                    // NOTE: Hookup the event handlers we care about on the web
                    //       client.  These are necessary because the file is
                    //       downloaded asynchronously.
                    //
                    webClient.DownloadProgressChanged +=
                        new DownloadProgressChangedEventHandler(
                            DownloadProgressChanged);

                    webClient.DownloadFileCompleted +=
                        new AsyncCompletedEventHandler(
                            DownloadFileCompleted);

                    //
                    // NOTE: Build the fully qualified path and file name,
                    //       within the temporary directory, where the file to
                    //       be downloaded will be saved.
                    //
                    fileName = Path.Combine(directory, fileName);

                    //
                    // NOTE: If the file name already exists (in the temporary)
                    //       directory, delete it.
                    //
                    // TODO: Perhaps an error should be raised here instead?
                    //
                    if (File.Exists(fileName))
                    {
                        File.Delete(fileName);
                    }

                    //
                    // NOTE: After kicking off the asynchronous file download
                    //       process, wait [forever] until the "done" event is
                    //       signaled.
                    //
                    Console.WriteLine(
                        "Downloading \"{0}\" to \"{1}\"...", uri, fileName);

                    webClient.DownloadFileAsync(uri, fileName);
                    doneEvent.WaitOne();
                }

                lock (syncRoot)
                {
                    return((int)exitCode);
                }
            }
            catch (Exception e)
            {
                //
                // NOTE: An exception was caught.  Report it via the console
                //       and return failure.
                //
                Error(e.ToString(), false);
                return((int)ExitCode.Exception);
            }
        }
 public void startWatch(EventHandler <ControllerRecord> watchDelegate)
 {
     watchThread      = new Thread(() => WatchTask(watchDelegate));
     watchCancelEvent = new EventWaitHandle(false, EventResetMode.ManualReset);
     watchThread.Start();
 }
Exemple #48
0
        public void OpenExisting_Windows()
        {
            string name = Guid.NewGuid().ToString("N");

            EventWaitHandle resultHandle;
            Assert.False(EventWaitHandle.TryOpenExisting(name, out resultHandle));
            Assert.Null(resultHandle);

            using (EventWaitHandle are1 = new EventWaitHandle(false, EventResetMode.AutoReset, name))
            {
                using (EventWaitHandle are2 = EventWaitHandle.OpenExisting(name))
                {
                    are1.Set();
                    Assert.True(are2.WaitOne(0));
                    Assert.False(are1.WaitOne(0));
                    Assert.False(are2.WaitOne(0));

                    are2.Set();
                    Assert.True(are1.WaitOne(0));
                    Assert.False(are2.WaitOne(0));
                    Assert.False(are1.WaitOne(0));
                }

                Assert.True(EventWaitHandle.TryOpenExisting(name, out resultHandle));
                Assert.NotNull(resultHandle);
                resultHandle.Dispose();
            }
        }
 public SyncEvents()
 {
     _newItemEvent = new AutoResetEvent(false);
     _exitThreadEvent = new ManualResetEvent(false);
     _eventArray = new WaitHandle[2];
     _eventArray[0] = _newItemEvent;
     _eventArray[1] = _exitThreadEvent;
 }
Exemple #50
0
 public void Ctor_StateMode(bool initialState, EventResetMode mode)
 {
     using (var ewh = new EventWaitHandle(initialState, mode))
         Assert.Equal(initialState, ewh.WaitOne(0));
 }
        private void InternalThreadProc(object state)
        {
            WaitCallback callBack = null;
            ThreadCount++;
            string name = Guid.NewGuid().ToString();

            EventWaitHandle handle = new EventWaitHandle(false, EventResetMode.AutoReset, name);

            //Thread.Sleep(1000);

            try
            {
                while (m_enabled)
                {
                    //Thread.Sleep(1000);

                    if (m_disposing)
                    {
                        return;
                    }

                    //Thread.Sleep(1000);

                    if (m_useFirstTime)
                    {
                        Notify.RunAppAtTime(string.Format(@"\\.\Notifications\NamedEvents\{0}", name), m_firstTime);
                        m_useFirstTime = false;
                    }
                    else
                    {
                        Notify.RunAppAtTime(string.Format(@"\\.\Notifications\NamedEvents\{0}", name), DateTime.Now.Add(m_interval));
                        m_firstTime = DateTime.MinValue;
                    }

                    //Thread.Sleep(1000);

                    if (m_disposing)
                    {
                        return;
                    }

                    int num = EventWaitHandle.WaitAny(new WaitHandle[] { handle, m_quitHandle });

                    //Thread.Sleep(1000);

                    if (num == 0)
                    {
                        m_cachedEnabled = null;

                        if (Tick != null)
                        {
                            if (callBack == null)
                            {
                                callBack = delegate { Tick(this, null); };
                            }
                            ThreadPool.QueueUserWorkItem(callBack);
                        }

                        //Thread.Sleep(1000);

                        if (OneShot)
                        {
                            //Thread.Sleep(1000);

                            if (m_cachedEnabled.HasValue)
                            {
                                //Thread.Sleep(1000);

                                m_enabled = m_cachedEnabled == true;

                                //Thread.Sleep(1000);
                            }
                            else
                            {
                                m_enabled = false;
                            }
                        }
                    }
                    else
                    {
                        m_enabled = false;
                    }
                }
            }
            finally
            {
                handle.Close();
                ThreadCount--;
                if (ThreadCount == 0)
                {
                    m_quitHandle.Reset();
                }
            }
        }
        internal bool EnableTransportManagerSendDataToClient(
            WSManNativeApi.WSManPluginRequest requestDetails,
            WSManPluginOperationShutdownContext ctxtToReport)
        {
            _shutDownContext = ctxtToReport;
            bool isRegisterWaitForSingleObjectSucceeded = true;

            lock (_syncObject)
            {
                if (_isRequestPending)
                {
                    // if a request is already pending..ignore this.
                    WSManPluginInstance.ReportWSManOperationComplete(
                        requestDetails,
                        WSManPluginErrorCodes.NoError);
                    return(false);
                }

                if (_isClosed)
                {
                    WSManPluginInstance.ReportWSManOperationComplete(requestDetails, _lastErrorReported);
                    return(false);
                }

                _isRequestPending = true;
                _requestDetails   = requestDetails;

                if (Platform.IsWindows)
                {
                    // Wrap the provided handle so it can be passed to the registration function
                    SafeWaitHandle  safeWaitHandle  = new SafeWaitHandle(requestDetails.shutdownNotificationHandle, false); // Owned by WinRM
                    EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
                    eventWaitHandle.SafeWaitHandle = safeWaitHandle;

                    _registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject(
                        eventWaitHandle,
                        new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback),
                        _shutDownContext,
                        -1,     // INFINITE
                        true);  // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION?
                    if (_registeredShutDownWaitHandle == null)
                    {
                        isRegisterWaitForSingleObjectSucceeded = false;
                    }
                }
                // release thread waiting to send data to the client.
                _waitHandle.Set();
            }

            if (!isRegisterWaitForSingleObjectSucceeded)
            {
                WSManPluginInstance.PerformCloseOperation(ctxtToReport);
                WSManPluginInstance.ReportOperationComplete(
                    requestDetails,
                    WSManPluginErrorCodes.ShutdownRegistrationFailed,
                    StringUtil.Format(
                        RemotingErrorIdStrings.WSManPluginShutdownRegistrationFailed));
                return(false);
            }

            return(true);
        }
Exemple #53
0
        private WaitCallback SetProfilerAttributes(Action <Action <StringDictionary> > process, string profilerKey,
                                                   string profilerNamespace, EventWaitHandle environmentKeyRead, EventWaitHandle processMgmt)
        {
            return(state =>
            {
                try
                {
                    process(dictionary =>
                    {
                        if (dictionary == null)
                        {
                            return;
                        }
                        SetProfilerAttributesOnDictionary(profilerKey, profilerNamespace, dictionary);

                        environmentKeyRead.Set();
                    });
                }
                finally
                {
                    processMgmt.Set();
                }
            });
        }
        public void MoveWithRMW(string home, string name)
        {
            paramEnv = null;
            paramDB  = null;

            // Open the environment.
            DatabaseEnvironmentConfig envCfg =
                new DatabaseEnvironmentConfig();

            envCfg.Create       = true;
            envCfg.FreeThreaded = true;
            envCfg.UseLocking   = true;
            envCfg.UseLogging   = true;
            envCfg.UseMPool     = true;
            envCfg.UseTxns      = true;
            paramEnv            = DatabaseEnvironment.Open(home, envCfg);

            // Open database in transaction.
            Transaction         openTxn = paramEnv.BeginTransaction();
            BTreeDatabaseConfig cfg     = new BTreeDatabaseConfig();

            cfg.Creation     = CreatePolicy.ALWAYS;
            cfg.Env          = paramEnv;
            cfg.FreeThreaded = true;
            cfg.PageSize     = 4096;
            // Use record number.
            cfg.UseRecordNumbers = true;
            paramDB = BTreeDatabase.Open(name + ".db", cfg, openTxn);
            openTxn.Commit();

            /*
             * Put 10 different, 2 duplicate and another different
             * records into database.
             */
            Transaction txn = paramEnv.BeginTransaction();

            for (int i = 0; i < 13; i++)
            {
                DatabaseEntry key, data;
                if (i == 10 || i == 11)
                {
                    key  = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("key"));
                    data = new DatabaseEntry(ASCIIEncoding.ASCII.GetBytes("data"));
                }
                else
                {
                    key  = new DatabaseEntry(BitConverter.GetBytes(i));
                    data = new DatabaseEntry(BitConverter.GetBytes(i));
                }
                paramDB.Put(key, data, txn);
            }

            txn.Commit();

            // Get a event wait handle.
            signal = new EventWaitHandle(false,
                                         EventResetMode.ManualReset);

            /*
             * Start RdMfWt() in two threads. RdMfWt() reads
             * and writes data into database.
             */
            Thread t1 = new Thread(new ThreadStart(RdMfWt));
            Thread t2 = new Thread(new ThreadStart(RdMfWt));

            t1.Start();
            t2.Start();

            // Give both threads time to read before signalling them to write.
            Thread.Sleep(1000);

            // Invoke the write operation in both threads.
            signal.Set();

            // Return the number of deadlocks.
            while (t1.IsAlive || t2.IsAlive)
            {
                /*
                 * Give both threads time to write before
                 * counting the number of deadlocks.
                 */
                Thread.Sleep(1000);
                uint deadlocks = paramEnv.DetectDeadlocks(DeadlockPolicy.DEFAULT);

                // Confirm that there won't be any deadlock.
                Assert.AreEqual(0, deadlocks);
            }

            t1.Join();
            t2.Join();
            paramDB.Close();
            paramEnv.Close();
        }
Exemple #55
0
        public void PingPong(EventResetMode mode)
        {
            // Create names for the two events
            string outboundName = Guid.NewGuid().ToString("N");
            string inboundName = Guid.NewGuid().ToString("N");

            // Create the two events and the other process with which to synchronize
            using (var inbound = new EventWaitHandle(true, mode, inboundName))
            using (var outbound = new EventWaitHandle(false, mode, outboundName))
            using (var remote = RemoteInvoke(PingPong_OtherProcess, mode.ToString(), outboundName, inboundName))
            {
                // Repeatedly wait for one event and then set the other
                for (int i = 0; i < 10; i++)
                {
                    Assert.True(inbound.WaitOne(FailWaitTimeoutMilliseconds));
                    if (mode == EventResetMode.ManualReset)
                    {
                        inbound.Reset();
                    }
                    outbound.Set();
                }
            }
        }
Exemple #56
0
 void init(bool manualReset)
 {
     h = new EventWaitHandle(false, (manualReset ? EventResetMode.ManualReset : EventResetMode.AutoReset));
 }
Exemple #57
0
        /// <summary>
        /// Report session context to WSMan..this will let WSMan send ACK to
        /// client and client can send data.
        /// </summary>
        internal void ReportContext()
        {
            int  result = 0;
            bool isRegisterWaitForSingleObjectFailed = false;

            lock (_syncObject)
            {
                if (true == isClosed)
                {
                    return;
                }

                if (!isContextReported)
                {
                    isContextReported = true;
                    PSEtwLog.LogAnalyticInformational(PSEventId.ReportContext,
                                                      PSOpcode.Connect, PSTask.None,
                                                      PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic,
                                                      creationRequestDetails.ToString(), creationRequestDetails.ToString());

                    //RACE TO BE FIXED - As soon as this API is called, WinRM service will send CommandResponse back and Signal is expected anytime
                    // If Signal comes and executes before registering the notification handle, cleanup will be messed
                    result = WSManNativeApi.WSManPluginReportContext(creationRequestDetails.unmanagedHandle, 0, creationRequestDetails.unmanagedHandle);
                    if (Platform.IsWindows && (WSManPluginConstants.ExitCodeSuccess == result))
                    {
                        registeredShutdownNotification = 1;

                        // Wrap the provided handle so it can be passed to the registration function
                        SafeWaitHandle  safeWaitHandle  = new SafeWaitHandle(creationRequestDetails.shutdownNotificationHandle, false); // Owned by WinRM
                        EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
                        eventWaitHandle.SafeWaitHandle = safeWaitHandle;

                        // Register shutdown notification handle
                        this.registeredShutDownWaitHandle = ThreadPool.RegisterWaitForSingleObject(
                            eventWaitHandle,
                            new WaitOrTimerCallback(WSManPluginManagedEntryWrapper.PSPluginOperationShutdownCallback),
                            shutDownContext,
                            -1,    // INFINITE
                            true); // TODO: Do I need to worry not being able to set missing WT_TRANSFER_IMPERSONATION?
                        if (this.registeredShutDownWaitHandle == null)
                        {
                            isRegisterWaitForSingleObjectFailed = true;
                            registeredShutdownNotification      = 0;
                        }
                    }
                }
            }

            if ((WSManPluginConstants.ExitCodeSuccess != result) || (isRegisterWaitForSingleObjectFailed))
            {
                string errorMessage;
                if (isRegisterWaitForSingleObjectFailed)
                {
                    errorMessage = StringUtil.Format(RemotingErrorIdStrings.WSManPluginShutdownRegistrationFailed);
                }
                else
                {
                    errorMessage = StringUtil.Format(RemotingErrorIdStrings.WSManPluginReportContextFailed);
                }

                // Report error and close the session
                Exception mgdException = new InvalidOperationException(errorMessage);
                Close(mgdException);
            }
        }
 public FileAcessSynch(string path)
 {
     _path       = path;
     _waitHandle = new EventWaitHandle(true, EventResetMode.AutoReset, Guid.NewGuid().ToString("N"));
 }
Exemple #59
0
		protected virtual void Dispose (bool disposing) 
		{
			if (disposing && !isDisposed) {
				isDisposed = true;
				if (waitHandle != null) {
					waitHandle.Dispose ();
					waitHandle = null;
				}
			}
		}
Exemple #60
0
        private WaitCallback ProcessBlock(IManagedCommunicationBlock communicationBlock, IManagedMemoryBlock memoryBlock,
                                          WaitHandle terminateThread, EventWaitHandle threadActivated, EventWaitHandle threadTerminated)
        {
            return(state =>
            {
                var processEvents = new []
                {
                    communicationBlock.ProfilerRequestsInformation,
                    memoryBlock.ProfilerHasResults,
                    terminateThread
                };
                threadActivated.Set();

                while (true)
                {
                    switch (WaitHandle.WaitAny(processEvents))
                    {
                    case 0:
                        _communicationManager.HandleCommunicationBlock(communicationBlock, (cB, mB) => { });
                        break;

                    case 1:
                        var data = _communicationManager.HandleMemoryBlock(memoryBlock);
                        // don't let the queue get too big as using too much memory causes
                        // problems i.e. the target process closes down but the host takes
                        // ages to shutdown; this is a compromise.
                        _messageQueue.Enqueue(data);
                        if (_messageQueue.Count > 400)
                        {
                            do
                            {
                                Thread.Yield();
                            } while (_messageQueue.Count > 200);
                        }
                        break;

                    case 2:
                        threadTerminated.Set();
                        return;
                    }
                }
            });
        }