c# - 不推荐使用的成员变量

标签 c# .net

根据MSDN ,由于线程和缓存,不建议使用成员变量。请注意,这个问题涉及多个领域,虽然我确定它主要与 .NET/C# 相关,但它可能结果特定于 CRM。它可能不会,但单挑可能是明智的。

虽然我对可能出现的问题了如指掌,但我不完全确定我理解准确和精确的情况,这些情况超出警告的范围。我关心的确切报价如下。

For improved performance, Microsoft Dynamics CRM caches plug-in instances. The plug-in's Execute method should be written to be stateless because the constructor is not called for every invocation of the plug-in. Also, multiple system threads could execute the plug-in at the same time. All per invocation state information is stored in the context, so you should not use global variables or attempt to store any data in member variables for use during the next plug-in invocation unless that data was obtained from the configuration parameter provided to the constructor. Changes to a plug-ins registration will cause the plug-in to be re-initialized.

我的类(class)是按照以下原则构建的。

public partial class Blopp : IPlugin
{
  private IPluginExecutionContext Context { get; set; }
  private Entity Target { get; set; }
  private IOrganizationService Service { get; set; }
  ...

  public Blopp() : this(String.Empty) { }
  public Blopp(String a) : this(a, String.Empty) { }
  public Blopp(String a, String b) { ... }

  public void Execute(IServiceProvider serviceProvider)
  {
    try
    {
      Assign(serviceProvider);
      DoStuff();
    }
    catch (Exception) { }
    finally { ... }
  }

  private void Assign(IServiceProvider serviceProvider) { ... }
}

现在,这个问题可能看起来很愚蠢,但是提到的全局变量 - 我的privatenon-static 字段不知何故是全局的?我会说他们不是,但我最近有点偏执,我想保持谦虚。

此外,当我访问上下文并分配字段时,我创建了一个新对象并一个一个地分配字段(不是每个类都有方法克隆) .序列化将要求我继承原始类,这违反了要求。这是一种足够可靠的方法吗? (请记住我新获得的偏执狂。)

我曾尝试在我的执行过程中造成问题,但据我所知,问题并没有出现。当然,没有证据并不是不存在的证据。我只是指出我不是懒惰发帖。而是意识到在比我最初看到的更深层次上的东西可能是错误的。

最佳答案

不,私有(private)成员不是全局变量。关键点是“您不应使用全局变量尝试将任何数据存储在成员变量中以便在下一次插件调用期间使用”

它表示,如果您在 Execute() 中操作您的私有(private)(或全局)变量,则 Execute() 的另一个调用可能会在同一实例上运行同时覆盖您的私有(private)(或全局)变量,导致在此之后运行的代码显示意外行为。

所以,让它们成为局部变量:

private void Assign(IServiceProvider serviceProvider) 
{
    IPluginExecutionContext context;
    Entity target;
    IOrganizationService service;

    ...
}

这将确保每个调用堆栈只访问它自己的变量。

关于c# - 不推荐使用的成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30506673/

相关文章:

c# - 作为配置属性的不可变类型

.net - LINQ : Generics with IQueryable

c# - 如何在不删除文件的情况下清除文本文件?

c# - 模型绑定(bind)是否通过 asp.net mvc 中的查询字符串工作

c# - 不支持在 xamarin.android 上使用 LINQ 连接 SQLite.Net 中的表

c# - 如何使/Home/Index重定向到/

c# - 在 C# 的声明或构造函数中初始化私有(private)对象

c# - OO 设计 - 减少一长串方法

c# - 如何获得对 Sql Compact 数据库的权限?

.net - Microsoft.ReportViewer.Common 版本=12.0.0.0