如何防止 .NET 运行时中的静态变量共享? [英] How do I prevent static variable sharing in the .NET runtime?

查看:61
本文介绍了如何防止 .NET 运行时中的静态变量共享?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个使用 Robocode-like 编程模型的游戏 (C#):参与者继承基类并添加策略行为.然后游戏加载参与者的课程实例,比赛开始.不幸的是,参与者可以通过在竞争对手 Class 的实例之间共享静态变量来作弊".

I'm working on a game (C#) that uses a Robocode-like programming model: participants inherit a base Class and add strategic behaviors. The game then loads instances of participants' Classes and the competition begins. Unfortunately, participants can "cheat" by sharing static variables between instances of their competitor Class.

如何防止 .NET 语言中 Class 实例之间的静态变量共享?我知道这是在 Java 中通过为每个实例使用单独的 ClassLoader 来完成的..NET 等价物是什么?

How do I prevent static variable sharing between Class instances in a .NET language? I know this is accomplished in Java by using a separate ClassLoader per instance. What's the .NET equivalent?

此外,我的测试表明,单独的 AppDomains 仅在加载扩展 MarshalByRefObject 的类时才有效.我想这是有道理的 - 如果您只是加载一个可序列化的类,该类会被复制到当前的 AppDomain 中,因此来自不同 AppDomain 的第二个对象将共享其静态变量.MarshalByRefObject 保证仅将代理加载到当前 AppDomain 中,而静态数据则留在加载的 AppDomain 中.另请参阅:http://blogs.msdn.com/ericlippert/archive/2004/05/27/143203.aspx

Further, my testing shows that separate AppDomains only work when loading a Class that extends MarshalByRefObject. I guess this makes sense - if you simply load a Serializable Class, the Class is copied into the current AppDomain so a second object from a different AppDomain will share its static vars. MarshalByRefObject guarantees that only a proxy is loaded into the current AppDomain and the statics stay behind in the loading AppDomain. See also: http://blogs.msdn.com/ericlippert/archive/2004/05/27/143203.aspx

推荐答案

将每个竞争对手加载到不同的 AppDomain.

Load each competitor into a different AppDomain.

这篇关于如何防止 .NET 运行时中的静态变量共享?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆