在调用Application.Restart之前,先在ApplicationContext中处理表单

本文关键字:ApplicationContext 处理 表单 先在 调用 Application Restart 之前 | 更新日期: 2023-09-27 18:29:49

我有一个winforms应用程序,它使用自定义应用程序上下文,该上下文提供了在系统托盘中运行应用程序的框架。

public partial class MyApplicationContext : ApplicationContext
{
    private IContainer components;
    private NotifyIcon notifyIcon = null;
    /// the main application form, which may never be shown
    private AppForm appForm = null;
    public MyApplicationContext() 
    {
        components = new System.ComponentModel.Container();
        notifyIcon = new NotifyIcon(components)
        {
            ContextMenuStrip = new ContextMenuStrip(),
            Icon = Properties.Resources.icon2a,
            Text = "Application",
            Visible = true
        };
        appForm = new AppForm();
    }
}

应用程序监视配置文件的更改,并在必要时重新启动自己。

private void requestRestart()
{
    /// dispose the application context
    this.Dispose(); 
    Application.Restart();
}

我必须在重新启动之前处理应用程序上下文,因为应用程序的新实例需要一些资源。然而,requestRestart()可以从另一个线程调用所以我不能在ApplicationContext.Dispose()方法中或直接在重新启动方法中处理appForm,否则我会得到一个跨线程异常。

如果在用户单击调用appForm.Show()的托盘图标时,表单在重新启动之前已显示,则会自动调用appForm.Dispose(true)。根据MSDN:

如果使用Show方法显示表单,则会自动调用Dispose。

否则,如果表单从未显示,GC终结器将调用Dispose(false)

如何确保在重新启动之前处理此表单?

在调用Application.Restart之前,先在ApplicationContext中处理表单

我建议您将appForm.Show()从构造函数中删除,并将其放入从任务栏图标调用的方法中。

在您的托盘图标打开形式方法中,将appForm.Show()包装在使用块中:

using (appForm = new AppForm()) {
    appForm.Show();
}

这样,每当窗体关闭时,它就会自行处理。

此外,在requestRestart()方法中放置以下内容:

appForm?.Close();

这将确保在上下文强制重新启动时关闭窗体。

如果你没有使用最新版本的.NET,下面的程序将实现同样的效果:

if (appForm != null)
    appForm.Close();

编辑

这是一个完整的例子。这个答案对你如何处理背景任务有点固执己见,但我认为你会发现它非常有效。

解释被内联为注释。

在您的程序.cs:

private static void Main()
{
    int restartCount = 0;
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    var applicationCtx = new MyApplicationContext();
    applicationCtx.RestartRequested += (o, e) =>
    {
        restartCount++; //this is just here so my program would stop restarting
        if (restartCount > 5) Application.Exit();
        Application.Restart();
    };
    Application.Run(applicationCtx);
}

然后在MyApplicationContext.cs:中

internal class MyApplicationContext : ApplicationContext
{
    private NotifyIcon notifyIcon;
    private IContainer components;
    private AppForm appForm;
    public event EventHandler RestartRequested;
    public MyApplicationContext()
    {
        notifyIcon = new NotifyIcon()
        {
            ContextMenuStrip = new ContextMenuStrip { Text = "Open Form" },
            Text = "Application",
            Visible = true,
            Icon = new Icon("icon.ico")
        };
        appForm = new AppForm();
        notifyIcon.DoubleClick += (o, e) =>
        {
            appForm.Show();
        };
        RestartRequested += (o, e) =>
        {
            appForm?.Close();  //Close() will dispose the form as well.
            notifyIcon?.Dispose();
        };
        BackgroundWork();
    }
    private void BackgroundWork()
    {
        Task.Run<bool>(() => //Here we are telling Task to run a background operation and return a bool
        {
            //this body will run in a separate thread
            Thread.Sleep(5000);  //this represents your background work
            var restart = true;  //whatever result the bg work yields
            return restart;
        }).ContinueWith((task) =>  //task is an instance of Task from above containing the result fromm the background work
        {
            var shouldRestart = task.Result;  // Result is the value you returned in the body Run body above
            if (shouldRestart) RestartRequested?.Invoke(this, EventArgs.Empty);
        },
        TaskScheduler.FromCurrentSynchronizationContext()); //This will return on the UI thread now, no need to worry about thread boundaries
    }
}
相关文章:
  • 没有找到相关文章