2010-04-15 16 views

回答

35

什麼很具體的例子這也許應該指出的是,創造AppDomains只是爲了讓周圍的東西,可以固定一個常量字符串可能是錯誤的方式做到這一點。使用非靜態輔助O)

static void Main(string[] args) 
{ 
    if (AppDomain.CurrentDomain.IsDefaultAppDomain()) 
    { 
     Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); 

     var currentAssembly = Assembly.GetExecutingAssembly(); 
     var otherDomain = AppDomain.CreateDomain("other domain"); 
     var ret = otherDomain.ExecuteAssemblyByName(currentAssembly.FullName, args); 

     Environment.ExitCode = ret; 
     return; 
    } 

    Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); 
    Console.WriteLine("Hello"); 
} 

快速樣品:如果你正在嘗試做同樣的事情,正如你指出的鏈接,你可能只是這樣做:

var configFile = Assembly.GetExecutingAssembly().Location + ".config"; 
if (!File.Exists(configFile)) 
    throw new Exception("do your worst!"); 

遞歸入口點入口點和MarshalByRefObject ...

class Program 
{ 
    static AppDomain otherDomain; 

    static void Main(string[] args) 
    { 
     otherDomain = AppDomain.CreateDomain("other domain"); 

     var otherType = typeof(OtherProgram); 
     var obj = otherDomain.CreateInstanceAndUnwrap(
           otherType.Assembly.FullName, 
           otherType.FullName) as OtherProgram; 

     args = new[] { "hello", "world" }; 
     Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); 
     obj.Main(args); 
    } 
} 

public class OtherProgram : MarshalByRefObject 
{ 
    public void Main(string[] args) 
    { 
     Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); 
     foreach (var item in args) 
      Console.WriteLine(item); 
    } 
} 
+1

謝謝。有沒有理由更喜歡一種方法對另一種? – 2010-04-15 20:18:42

+0

第一個可能會更乾淨。它可以讓你使用標準的入口點,而不必創建一個需要在appdomains之間編組的對象。第二種方法更典型。但它通常用於插件,而不是應用程序的主要入口點。 – 2010-04-15 20:22:27

+1

AppDomain對象上還有一個'.ExecuteAssembly(...)'方法,您可以提供包含入口點的另一個程序集的路徑。這可能允許稍微更簡潔的設計,但至少需要兩個組件。 – 2010-04-15 20:25:30

4

您需要:

1)創建AppDomainSetup對象的實例,並通過使用AppDomain.CreateDoman方法你想要的設置信息,爲您的域名

2)創建新的域來填充它。具有配置參數的AppDomainSetup實例被傳遞給CreateDomain方法。

3)通過在域對象上使用CreateInstanceAndUnwrap方法在新域中創建對象的實例。這種方法需要你想創建的對象的類型名稱,並返回一個遠程代理,你可以在你的主域中使用它來與新的對象進行通信。

一旦你完成了這3個步驟,你可以調用方法通過代理的其他域。您也可以在完成後卸載域並重新加載。

topic在MSDN幫助有需要

+2

這或多或少是我在其他地方看到的例子,但不提供任何我仍然缺乏的信息。 我只是調用Application.Run(new MyForm)? 我是否從我的Main方法中刪除了所有現有的啓動代碼,將它放在一個新的方法中,然後調用它來啓動我的應用程序? 以上都不是,因爲我比我想象的更困惑? – 2010-04-15 20:03:46

+1

您嘗試獲取代理的對象必須是'MarshalByRefObject',否則它只會嘗試將副本序列化回原始AppDomain。 – 2010-04-15 20:13:34

+0

@Matthew Whited - 你是對的,我忘了提及 – mfeingold 2010-04-15 20:23:22

相關問題