• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Mutex类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Mutex的典型用法代码示例。如果您正苦于以下问题:C# Mutex类的具体用法?C# Mutex怎么用?C# Mutex使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



Mutex类属于命名空间,在下文中一共展示了Mutex类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Run

    private int Run()
    {
        int iRet = -1;
        string sName = Common.GetUniqueName();
        // Basic test, not owned
        using(mut = new Mutex(false, sName))
        {
            Thread t = new Thread(new ThreadStart(OwnMutex));
            t.Start();
            mre.WaitOne();
            try
            {
                Mutex mut1 = Mutex.OpenExisting(sName);
                mut1.WaitOne();
                mut1.ReleaseMutex();
                iRet = 100;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unexpected exception thrown: " +
                    ex.ToString());
            }
        }

        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:27,代码来源:openmutexpos1.cs


示例2: Main

    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);

        var zzz = new z();
        bool createdNew;
        #if DEBUG || RELEASE_TEST

        #else

        Mutex instance = new Mutex(true, zzz.GetType().ToString(), out createdNew);

        if (!createdNew)
        {
            MessageBox.Show("不能多开");
            return;
        }
        #endif
        try
            {

                Application.Run(zzz);
                //Application.Run(new ShipForm());
            }
            catch (Exception e)
            {
                write_dump(e.ToString());
            }
        //var f = new CommandForm();
        //Application.Run(f);
    }
开发者ID:lavender1213,项目名称:ShipGirlBot,代码行数:34,代码来源:Program.cs


示例3: OpenExisting_Windows

    public void OpenExisting_Windows()
    {
        string name = Guid.NewGuid().ToString("N");

        Mutex resultHandle;
        Assert.False(Mutex.TryOpenExisting(name, out resultHandle));

        using (Mutex m1 = new Mutex(false, name))
        {
            using (Mutex m2 = Mutex.OpenExisting(name))
            {
                Assert.True(m1.WaitOne(FailedWaitTimeout));
                Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
                m1.ReleaseMutex();

                Assert.True(m2.WaitOne(FailedWaitTimeout));
                Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
                m2.ReleaseMutex();
            }

            Assert.True(Mutex.TryOpenExisting(name, out resultHandle));
            Assert.NotNull(resultHandle);
            resultHandle.Dispose();
        }
    }
开发者ID:noahfalk,项目名称:corefx,代码行数:25,代码来源:MutexTests.cs


示例4: Awake

	void Awake()
	{
		SetupWebCamTexture();
		InitializeAruco();

		mutex_ = new Mutex();
		thread_ = new Thread(() => {
			try {
				for (;;) {
					Thread.Sleep(0);
					if (!isArucoUpdated_) {
						mutex_.WaitOne();
						var num = aruco_detect(aruco_, false);
						GetMarkers(num);
						mutex_.ReleaseMutex();
						isArucoUpdated_ = true;
					}
				}
			} catch (Exception e) {
				if (!(e is ThreadAbortException)) {
					Debug.LogError("Unexpected Death: " + e.ToString());
				}
			}
		});

		thread_.Start();
	}
开发者ID:AndroidHMD,项目名称:unity-android-aruco-sample,代码行数:27,代码来源:ArPlane.cs


示例5: Run

    private int Run()
    {
        int iRet = -1;
        string sName = Common.GetUniqueName();
        //  open a Mutex that has been abandoned
        mut = new Mutex(false, sName);
        Thread th = new Thread(new ParameterizedThreadStart(AbandonMutex));
        th.Start(mut);
        mre.WaitOne();
        try
        {
            Mutex mut1 = Mutex.OpenExisting(sName);
            mut1.WaitOne();
        }
        catch (AbandonedMutexException)
        {
            //Expected	
            iRet = 100;
        }
        catch (Exception e)
        {
            Console.WriteLine("Caught unexpected exception: " + 
                e.ToString());
        }

        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:28,代码来源:openmutexneg7.cs


示例6: Run

    private int Run()
    {
        int iRet = -1;
        string sName = Common.GetUniqueName();
        // Open an abandoned mutex
        using (mut = new Mutex(false, sName))
        {
            Thread t = new Thread(new ThreadStart(AbandonMutex));
            t.Start();
            t.Join();
            try
            {
                Mutex mut1 = Mutex.OpenExisting(sName);
                iRet = 100;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Unexpected exception thrown: " +
                    ex.ToString());
            }
        }

        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:25,代码来源:openmutexpos3.cs


示例7: Run

    private int Run()
    {
        int iRet = -1;
        string sName = Common.GetUniqueName();
        //  open a semaphore with the same name as a mutex
        Mutex mu = new Mutex(false, 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;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:26,代码来源:semaphoreopenneg6.cs


示例8: GetDefaultUsername

#pragma warning restore 0414

	private string GetDefaultUsername()
	{
		var count = 0;
		while (true)
		{
			var name = string.Format("{0}_{1}_{2}", Application.companyName, Application.productName, count);

			bool created;
			m_nameMutex = new Mutex(true, name, out created);
			if (created)
			{
				break;
			}

			count++;
		}

		var username = Environment.UserName;
		if (count > 0)
		{
			username = string.Format("{0} ({1})", username, count);
		}

		return username;	
	}
开发者ID:returnString,项目名称:metagame.unity,代码行数:27,代码来源:Game.cs


示例9: OpenExisting

    public void OpenExisting()
    {
        const string Name = "MutexTestsOpenExisting";

        Mutex resultHandle;
        Assert.False(Mutex.TryOpenExisting(Name, out resultHandle));

        using (Mutex m1 = new Mutex(false, Name))
        {
            using (Mutex m2 = Mutex.OpenExisting(Name))
            {
                Assert.True(m1.WaitOne());
                Assert.False(Task.Factory.StartNew(() => m2.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
                m1.ReleaseMutex();

                Assert.True(m2.WaitOne());
                Assert.False(Task.Factory.StartNew(() => m1.WaitOne(0), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Result);
                m2.ReleaseMutex();
            }

            Assert.True(Mutex.TryOpenExisting(Name, out resultHandle));
            Assert.NotNull(resultHandle);
            resultHandle.Dispose();
        }
    }
开发者ID:johnhhm,项目名称:corefx,代码行数:25,代码来源:MutexTests.cs


示例10: Run

    private int Run()
    {
        int iRet = -1;
        Console.WriteLine("Abandon same named mutex");
        // Create array with the same name
        wh = new Mutex[2];
        string sName = Common.GetUniqueName();
        wh[0] = new Mutex(false, sName);
        wh[1] = new Mutex(false, sName);

        Thread t = new Thread(new 
            ParameterizedThreadStart(this.AbandonMutexPos));
        t.Start(0);
        t.Join();
        try
        {
            Console.WriteLine("Waiting...");
            int i = WaitHandle.WaitAny(wh, 5000);
            Console.WriteLine("WaitAny did not throw an " +
                "exception, i = " + i);
        }
        catch(AbandonedMutexException)
        {
            // Expected
            iRet = 100;
        }
        catch(Exception e)
        {
            Console.WriteLine("Unexpected exception thrown: " + 
                e.ToString());
        }
        Console.WriteLine(100 == iRet ? "Test Passed" : "Test Failed");
        return iRet;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:34,代码来源:waitanyex8.cs


示例11: Main

        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            // Application.Run(new FormLineCanon());
			
			// CurrentUser=new User();
            // Giá trị luận lý cho biết ứng dụng này
            // có quyền sở hữu Mutex hay không.
            bool ownmutex;

            // Tạo và lấy quyền sở hữu một Mutex có tên là Icon;
            using (var mutex = new Mutex(true, "Icon", out ownmutex))
            {
                // Nếu ứng dụng sở hữu Mutex, nó có thể tiếp tục thực thi;
                // nếu không, ứng dụng sẽ thoát.
                if (ownmutex)
                {
                    // Application.Run(new FormLogin());
					Application.Run(new FormLogin());
                    //giai phong Mutex;
                    mutex.ReleaseMutex();
                }
                else
                    Application.Exit();
            } 
        }
开发者ID:cuongpv88,项目名称:work,代码行数:27,代码来源:Program.cs


示例12: Main

 public static int Main(String[] args)
   {
   Console.WriteLine("MutexSample.cs ...");
   gM1 = new Mutex(true,"MyMutex");			
   gM2 = new Mutex(true);						
   Console.WriteLine(" - Main Owns gM1 and gM2");
   AutoResetEvent[]	evs	= new AutoResetEvent[4];
   evs[0] = Event1;			
   evs[1] = Event2;			
   evs[2] = Event3;			
   evs[3] = Event4;			
   MutexSample			tm	= new MutexSample( );
   Thread				t1	= new Thread(new ThreadStart(tm.t1Start));
   Thread				t2	= new Thread(new ThreadStart(tm.t2Start));
   Thread				t3	= new Thread(new ThreadStart(tm.t3Start));
   Thread				t4	= new Thread(new ThreadStart(tm.t4Start));
   t1.Start( );				
   t2.Start( );				
   t3.Start( );				
   t4.Start( );				
   Thread.Sleep(2000);
   Console.WriteLine(" - Main releases gM1");
   gM1.ReleaseMutex( );		
   Thread.Sleep(1000);
   Console.WriteLine(" - Main releases gM2");
   gM2.ReleaseMutex( );		
   WaitHandle.WaitAll(evs);	
   Console.WriteLine("... MutexSample.cs");
   return 0;
   }
开发者ID:ArildF,项目名称:masters,代码行数:30,代码来源:cs_mutexsample.cs


示例13: ReuseMutexThread

    public void ReuseMutexThread()
    {
        Console.WriteLine("Waiting to reuse mutex");
        manualEvent.WaitOne();
        bool exists;

        Mutex mutex = new Mutex(true, mutexName, out exists);
		
		if (exists)
		{
			Console.WriteLine("Error, created new mutex!");
			success = 97;
		}
		else
		{
			mutex.WaitOne();
		}

		
        try
        {
            Console.WriteLine("Mutex reused {0}", exists);
            mutex.ReleaseMutex();
        }
        catch (Exception e)
        {
            Console.WriteLine("Unexpected exception: {0}", e);
            success = 98;
        }

        exitEvent.Set();
    }
开发者ID:geoffkizer,项目名称:coreclr,代码行数:32,代码来源:openmutexpos4.cs


示例14: Main

    static void Main()
    {
        bool isFirstInstance;
        var mutex = new Mutex(true, "VolumeWheelEx", out isFirstInstance);

        if(isFirstInstance) {

            try {
                Hook.SetHook();
                var exit = false;
                while(!exit) { try { exit = WinAPI.GetMessage(IntPtr.Zero, IntPtr.Zero, 0, 0) > 0; } catch(NullReferenceException) { /* Don't worry, GetMessage can sometimes returns NULL. */ } };
                Hook.UnHook();
            } catch(Exception e) {
                //LOG file directly on desktop
                System.IO.File.AppendAllText(Environment.GetEnvironmentVariable("userprofile") + "\\Desktop\\VolumeWheelEx.log", "[" + DateTime.Now.ToString() + "]\n" + e.Source + " -> " + e.ToString() + "\n" + e.StackTrace + "\n\n");
            } finally {
                mutex.ReleaseMutex();
            }

        } else {

            try {
                var thisProc = Process.GetCurrentProcess();
                var prcs = Process.GetProcessesByName(thisProc.ProcessName);
                for(int i = 0; i < prcs.Length; i++) {
                    if(prcs[i].Id != thisProc.Id) {
                        WinAPI.PostThreadMessage((uint)prcs[i].Threads[0].Id, WinAPI.WM_QUIT, UIntPtr.Zero, IntPtr.Zero);
                    }
                }
            } catch { }

        }
    }
开发者ID:HanabishiRecca,项目名称:VolumeWheelEx,代码行数:33,代码来源:Program.cs


示例15: PosTest1

    public bool PosTest1()
    {
        bool retVal = true;
        Thread thread = null;

        // Add your scenario description here
        TestLibrary.TestFramework.BeginScenario("PosTest1: Construct a new Mutex instance with initiallyOwned set to true (ensure that the thread owns the mutex)");

        using(m_Mutex = new Mutex(true))
        {
            try
            {
                do
                {
                    if (null == m_Mutex)
                    {
                        TestLibrary.TestFramework.LogError("001", "Can not construct a new Mutex intance with initiallyOwned set to true.");
                        retVal = false;

                        break;
                    }

                    // Ensure initial owner of the mutex is current thread 

                    // Create another thread to change value of m_SharedResource
                    thread = new Thread(new ThreadStart(ThreadProc));
                    thread.Start();

                    // Sleep 1 second to wait the thread get started
                    Thread.Sleep(c_DEFAULT_SLEEP_TIME);

                    if (m_SharedResource != c_DEFAULT_INT_VALUE)
                    {
                        TestLibrary.TestFramework.LogError("002", "Call Mutex(true) does not set current thread to be the owner of the mutex.");
                        retVal = false;
                    }
                    m_Mutex.ReleaseMutex();
                } while (false); // do
            }
            catch (Exception e)
            {
                TestLibrary.TestFramework.LogError("003", "Unexpected exception: " + e);
                TestLibrary.TestFramework.LogInformation(e.StackTrace);
                retVal = false;
            }
            finally
            {
                if (null != thread)
                {
                    // Wait until all threads are terminated
                    thread.Join();
                }

                // Reset the value of m_SharedResource for further usage
                m_SharedResource = c_DEFAULT_INT_VALUE;
            }
        }

        return retVal;
    }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:60,代码来源:mutexctor1.cs


示例16: CreateMutexArray

 private void CreateMutexArray(int numElements)
 {
     wh = new WaitHandle[numElements];
     for(int i=0;i<numElements;i++)
     {
         wh[i] = new Mutex();
     }
 }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:8,代码来源:waitallex8a.cs


示例17: T3start

 public void T3start() {
 Console.WriteLine("In T3 start, Mutex.WaitAny(Mutex[])");
 Mutex[] gMs = new Mutex[2];
 gMs[0] = gM1; gMs[1] = gM2;
 Mutex.WaitAny(gMs);
 Console.WriteLine("T3 finished, Mutex.WaitAny(Mutex[])");
 Event3.Set();
 }
开发者ID:ArildF,项目名称:masters,代码行数:8,代码来源:cs_mutex2.cs


示例18: CreateMutexArray

 private void CreateMutexArray(int numElements)
 {
     wh = new WaitHandle[numElements];
     for(int i=0;i<numElements;i++)
     {
         wh[i] = new Mutex(false, Common.GetUniqueName());
     }
 }
开发者ID:CheneyWu,项目名称:coreclr,代码行数:8,代码来源:waitallex8.cs


示例19: WaitAllSameNames

    public static void WaitAllSameNames()
    {
        Mutex[] wh = new Mutex[2];
        wh[0] = new Mutex(false, "test");
        wh[1] = new Mutex(false, "test");

        Assert.Throws<ArgumentException>(() => WaitHandle.WaitAll(wh));
    }
开发者ID:johnhhm,项目名称:corefx,代码行数:8,代码来源:WaitHandle.cs


示例20: T1start

 public void T1start() {
 Console.WriteLine("In T1 start, Mutex.WaitAll(Mutex[])");
 Mutex[] gMs = new Mutex[2];
 gMs[0] = gM1; gMs[1] = gM2;
 Mutex.WaitAll(gMs);
 Thread.Sleep(2000);
 Console.WriteLine("T1 finished, Mutex.WaitAll(Mutex[])");
 Event1.Set();
 }
开发者ID:ArildF,项目名称:masters,代码行数:9,代码来源:cs_mutex2.cs



注:本文中的Mutex类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# MvcContext类代码示例发布时间:2022-05-24
下一篇:
C# MutableString类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap