首页 > 解决方案 > C# 在两个不同的 Windows 窗体之间使用互斥锁有条件地执行方法

问题描述

我在 C# 中有两个不同的 Windows 窗体应用程序,它们运行不同的程序。其中一个窗口应该在后台更新包含内容的文件夹。另一种形式要么闲置在菜单中,要么玩依赖于在后台下载的内容的游戏。

当用户在以其他形式更新内容时玩游戏时会出现我的问题。

我一直在研究使用互斥锁在两个表单之间进行通信,这样当用户在主表单上的游戏中时,后台表单在用户退出游戏之前不会更新任何内容。

我以前从未使用过互斥锁,我正在寻求一些帮助来设置它们。

这是我的背景表单的构造函数。

    /// <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.";
        }
    }

它监视进程主窗体。

这是在后台表单运行时更新上下文的方法,它是从 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;
    }

如果正在运行来自构造函数的进程,我不确定如何在此代码中实现互斥锁以不允许更新内容。

任何帮助,将不胜感激。:)

标签: c#winforms

解决方案


程序 1

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

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

节目二

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

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

推荐阅读