简体   繁体   English

通过两个不同的客户端调用在两个服务之间共享变量

[英]Share variable between two services with two different client call

I want to share a variable between two services when calling two client proxies. 我想在调用两个客户端代理时在两个服务之间共享一个变量。 (And also variable should be shared per session) My sample code as below, (并且每个会话还应共享变量)我的示例代码如下,

** Server ** **服务器**

Service 1 服务1

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class MyService : IMyService
{
    public string SharedValue = string.Empty;

    public void SETValue(string inputString)
    {
        SharedValue = inputString;
    }
}

[ServiceContract(SessionMode = SessionMode.Required)]
public interface IMyService
{
    [OperationContract(IsOneWay = true)]
    void SETValue(string inputString);
}

Service 2 服务2

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class MyService2 : MyService, IMyService2
{
    public string GETSharedValue()
    {
        return base.SharedValue;   //This value got Empty
    }
}

[ServiceContract(SessionMode = SessionMode.Required)]
public interface IMyService2
{
    [OperationContract]
    string GETSharedValue();
}

I'm using 'wsHttpBinding' for both services. 我为两个服务都使用“ wsHttpBinding”。

** Client ** **客户**

    private string sharedValue = string.Empty;
    MyServiceReference.MyServiceClient client = null;
    MyService2Reference.MyService2Client client2 = null;

    public Form1()
    {
        InitializeComponent();

        client = new MyServiceReference.MyServiceClient();
        client2 = new MyService2Reference.MyService2Client();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        client.SETValue("Hello this is client 1");

        sharedValue = client2.GETSharedValue();
        lblResult.Text = sharedValue;
    }

write a class with a static variable eg: 用静态变量编写一个类,例如:

public static class  SharedValues

    { 
       public static String SharedValue = string.Empty;
    }

then use 然后使用

 public void SETValue(string inputString)
    {
        SharedValues.SharedValue = inputString;
    }

if you want concurrency cosider using a lock statement 如果要使用lock语句进行并发合并

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

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