C#之不同程序域数据交互🔥
CZerocheng 1/24/2024 CSharp
在C#中,要将新应用程序域中的数据传递到主应用程序域,需要使用一种跨应用程序域通信的机制。以下是一种常见的方法实现跨应用程序域通信,并将数据传递回主应用程序域: 首先,我们创建一个实现了MarshalByRefObject的可远程对象:
public class DataProvider : MarshalByRefObject
{
private string _data;
public string GetData()
{
Console.WriteLine($"DataProvider中的域ID:{AppDomain.CurrentDomain.Id}");
return _data;
}
public void SetData(string data)
{
_data = data;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
然后,在主应用程序域中创建一个DataProvider对象,并将其传递给新应用程序域,以便在新应用程序域中操作数据:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NewDomainDemo
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine($"Main中的域ID:{AppDomain.CurrentDomain.Id}");
// 创建一个新的应用程序域
AppDomain newDomain = AppDomain.CreateDomain("NewAppDomain");
// 在新应用程序域中创建 DataProvider 对象
DataProvider provider = (DataProvider)newDomain.CreateInstanceAndUnwrap(
typeof(DataProvider).Assembly.FullName, typeof(DataProvider).FullName);
// 在新应用程序域中设置数据
provider.SetData("Data from new AppDomain");
// 在主应用程序域中获取数据
string data = provider.GetData();
Console.WriteLine($"Main中的域ID:{AppDomain.CurrentDomain.Id}");
Console.WriteLine("Data received in main AppDomain: " + data);
// 卸载应用程序域
AppDomain.Unload(newDomain);
Console.ReadLine();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
在这个示例中,我们在主应用程序域中创建了一个DataProvider对象,并将其传递给新创建的应用程序域。然后,在新应用程序域中设置了数据。最后,在主应用程序域中通过远程对象调用获取数据的方法来获取新应用程序域中的数据。