日期:2014-05-18  浏览次数:20810 次

|300分應用程序域討論|關閉先創建的AppDomain的窗體,會導致後打開的AppDomain的窗體也關閉!
創建一個Windows應用程序,新建一個Form,添加一個Button,Button的Click事件代碼如下: 

C#版本代碼 
C# code

        private void button1_Click(object sender, EventArgs e)
        {
            AppDomain domain = AppDomain.CreateDomain("newdomain");
            domain.ExecuteAssemblyByName(Assembly.GetExecutingAssembly().FullName);
        }



VB版本代碼 
VB.NET code

        Private Sub Button1_Click(ByVal sender As Object ,ByVal e As EventArgs)
            Dim domain As AppDomain= AppDomain.CreateDomain("newdomain")
            domain.ExecuteAssemblyByName(Assembly.GetExecutingAssembly().FullName)
        End Sub



編譯,運行,在窗口上連續點擊按鈕,會彈出幾個新的窗體(創建了新的應用程序域)。 
關閉某個先打開的窗體,會發現在該窗體之後打開的窗體都會關閉!如果把後打開的窗體先關閉,就不會有這個問題。 

是何原因?如何解決? 如果問題能夠解決,再加100分.

PS:此貼內有雅座,原地址為http://topic.csdn.net/u/20080321/14/3359dc4a-49ea-4a7c-be52-40863e45ca1c.html,因CSDN之BUG導致該貼無法在.NET大版顯示,故重發。也可於該貼內討論。


------解决方案--------------------
我觉得是 变量作用域 的原因。

AppDomain domain = AppDomain.CreateDomain("newdomain");
是声明在按钮事件里,这个窗体关掉时,声明的AppDomain也关掉了,所以后建的窗体会依次关掉。


------解决方案--------------------
星级高发问,学习
------解决方案--------------------
这样就以了随意关闭窗口了
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(tt));
t.Start();

}

private static void tt()
{

AppDomain domain = AppDomain.CreateDomain("newdomain");
domain.ExecuteAssemblyByName(Assembly.GetExecutingAssembly().FullName);
}
------解决方案--------------------
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
AppDomain domain = AppDomain.CreateDomain("newdomain");
domain.ExecuteAssemblyByName(Assembly.GetExecutingAssembly().FullName);

}

private void button2_Click(object sender, EventArgs e)
{
Form f = new Form();
f.Text = System.DateTime.Now.ToString();
f.Show();
}
}
}
1、当 Form1关闭所有的窗口关闭,所有窗口关闭
2、当点button2_Click后,弹出的新的应用界面窗口
3、新的应用界面窗口点button2_Click,弹出f,当新的应用界面关闭,新的f关闭,最先打开的主界面还在
4、最初打开的Form1,则关闭所有界面,包括新的应用界面
------解决方案--------------------
亦可试试:

private int i = 0;

AppDomain.CreateDomain("newdomain" + this.i++);
------解决方案--------------------
cdsgajxlp 的办法会导致关闭不了线程吗?