简体   繁体   English

C#在两个不同的Windows窗体之间使用互斥体有条件地执行方法

[英]C# Using Mutexes between two different Windows Forms to execute method conditionally

I have two different windows forms applications in C# that run off of different programs. 我在C#中有两个不同的Windows窗体应用程序,它们可以从不同的程序运行。 One of the windows is supposed to update a folder with content in the background. 其中一个窗口应该在后台更新包含内容的文件夹。 The other form either sits idle in a menu, or plays a game that relies on the content that has been downloaded in the background. 另一种形式是要么闲置在菜单中,要么玩依赖于已在后台下载的内容的游戏。

My issue occurs when the user plays the game while the content is being updated in the other form. 我的问题发生在用户以其他形式更新内容的同时玩游戏时。

I have been looking into using Mutexes to communicate between the two forms so that when the user is in the game on the main form, the background form does not update any content until the user exits the game. 我一直在研究使用Mutexes在两种形式之间进行通信,以便当用户在主形式上的游戏中时,后台形式在用户退出游戏之前不会更新任何内容。

I have never used Mutexes before and I am looking for some help setting them up. 我以前从未使用过Mutexes,并且正在寻找一些帮助来设置它们。

This is the constructor of my background form. 这是我的背景表单的构造函数。

    /// <summary>
    /// Initialises an instance of the <see cref="GameReviewManager" /> class.
    /// </summary>
    public GameReviewManager()
    {
        _initialStartup = false;

        InitializeComponent();

        _launcher = new Process();
        _launcher.StartInfo.FileName = "GameReviewLauncher";
        _launcher.EnableRaisingEvents = true;
        _launcher.Exited += LauncherExited;

        if (!GamesFolderEmpty())
        {
            _launcher.Start();
            _initialStartup = true;
        }
        else
        {
            textLabel.Text = "Copying content, please wait.";
        }
    }

It monitors the process main form. 它监视过程的主要形式。

Here is the method that updates the context while the background form is running, it is called from the Shown event. 这是在后台表单运行时更新上下文的方法,该方法从Shown事件中调用。

    /// <summary>
    /// Monitors the directory at path, copies any changes made.
    /// </summary>
    /// <param name="path">The path to monitor.</param>
    private void MonitorDirectory(string path)
    {
        //Now Create all of the directories
        foreach (string dirPath in Directory.GetDirectories(path, "*", SearchOption.AllDirectories))
        {
            Directory.CreateDirectory(dirPath.Replace(path, GamesDirectory));
        }

        //Copy all the files & Replaces any files with the same name
        foreach (string newPath in Directory.GetFiles(path, "*", SearchOption.AllDirectories))
        {
            if (newPath.Substring(newPath.Length - 4) != ".ini")
            {
                string destination = newPath.Replace(path, GamesDirectory);
                File.Copy(newPath, newPath.Replace(path, GamesDirectory), true);
                Console.WriteLine("File added: {0}", destination);

                if (!string.IsNullOrWhiteSpace(progressTextBox.Text))
                {
                    progressTextBox.AppendText("\r\n" + $"File added: {destination}");
                    progressTextBox.ScrollToCaret();
                }
                else
                {
                    progressTextBox.AppendText($"File added: {destination}");
                    progressTextBox.ScrollToCaret();
                }
            }
        }

        progressTextBox.AppendText("\r\n\r\n" + "Content copied successfully.");
        progressTextBox.ScrollToCaret();

        FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
        fileSystemWatcher.Path = path;
        fileSystemWatcher.Created += FileSystemWatcherCreated;
        fileSystemWatcher.Renamed += FileSystemWatcherRenamed;
        fileSystemWatcher.Deleted += FileSystemWatcherDeleted;
        fileSystemWatcher.Changed += FileSystemWatcherChanged;
        fileSystemWatcher.EnableRaisingEvents = true;
    }

I am not sure how to implement the mutex into this code to not allow the content to be updated if the process from the constructor is being run. 我不确定如何在此代码中实现互斥锁,以防止在运行构造函数的过程时更新内容。

Any help would be appreciated. 任何帮助,将不胜感激。 :) :)

Program 1 程序1

public void DownloadForm1()
{
   using (var m = new Mutex(true, "SomeAwesomeName"))
   {
      m.WaitOne();

      try
      {
         // code to protect here
      }
      finally
      {
         m.ReleaseMutex();
      }
   }
}

Program 2 程序2

public void ProcessForm2()
{
   using (var m = new Mutex(true, "SomeAwesomeName"))
   {
      m.WaitOne();

      try
      {
         // code to protect here
      }
      finally
      {
         m.ReleaseMutex();
      }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM