简体   繁体   English

从2个不同的应用程序访问类库的公共变量

[英]Accessing the public variable of class library from 2 different application

I have a class library developed in c# which has something similar as shown below. 我有一个用c#开发的类库,它具有如下所示的类似内容。 It has a class ClassLib . 它具有ClassLib类。 It has one public variable somevariable and 2 methods.One method assigns the value to this variable and one method uses this variable. 它具有一个public变量somevariable和2种方法。一种方法将值分配给此变量,另一种方法使用此变量。

class ClassLib
{
    public string somevariable;
    public void SomeMethod1()
    {
        somevariable = "someData";
    }
    public void SomeMethod2()
    {
        string finalValue = somevariable;
    }
}

Now I have 2 different windows services, in which this class library is being referenced to. 现在,我有2个不同的Windows服务,其中引用了该类库。

In Windows Service 1 , it has some similar code. Windows Service 1中 ,它具有一些类似的代码。

public class Application1
{
    public void AppMethod1()
    {
        ClassLib c1 = new ClassLib();
        c1.somevariable = "Application 1 Data";
        c1.SomeMethod2();
    }
}

This class is assigning the value to the public variable and calling the second method to use it. 此类将值分配给公共变量并调用第二种方法来使用它。

Windows Service 2 : Windows Service 2:

public class Application2
{
    public void AppMethod2()
    {
        ClassLib c1 = new ClassLib();
        c1.SomeMethod1();
        c1.SomeMethod2();
    }
}

This calls both the methods. 这将调用这两种方法。
These 2 windows services run continuously.So now my question is, if both services are running simultaneously and referencing to same class in class library, will this effect the value of somevariable . 这两个Windows服务连续运行。所以现在我的问题是,如果两个服务同时运行并引用类库中的同一类,这将影响somevariable的值。 Since one application is assigning the value and one is trying to use the existing value from SomeMethod1 . 由于一个应用程序正在分配值,而另一个正在尝试使用SomeMethod1的现有值。
In other words, in WindowsService2 , when c1.SomeMethod2() is called, will the value of somevariable be "Application 1 Data" at any point of time? 换句话说,在WindowsService2中,当c1.SomeMethod2()时,在任何时间点somevariable的值都将是"Application 1 Data"吗? Will the values overlap? 这些值会重叠吗?

No. Each Windows Service runs as its own process, meaning it has its own heap. 否。每个Windows服务都作为自己的进程运行,这意味着它具有自己的堆。 So there is no shared memory between the two services, even though they reference the same DLL. 因此,即使两个服务引用相同的DLL,也没有共享内存。

There are ways to create data that are shared between processes, but only if the code does something unusual. 有多种方法可以创建在进程之间共享的数据,但前提是代码需要执行一些不寻常的操作。 Normal variables are not shared. 普通变量不共享。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM