How to make a shared class that holds cacthed data?

T

Trung

Hi everybody

I write a class named SharedClass that holds catched data that would be
available for all clients by using static method/member.

This class is registered in the assembly folder. And I write 2 client
applications Client1 and Client2 that use SharedClass. But Client2 cannot
get the value that given to SharedClass by Client1.

How can I make SharedClass' data available for all clients? Source code is
attached.

Thanks

Trung

//-----------------------------
SharedClass.cs ---------------------------------
using System;
namespace SharedClasses
{
public class SharedClass
{
private static int intSharedValue = 0;
public SharedClass(){}
public static int Value
{
get
{
return intSharedValue;
}
set
{
intSharedValue = value;
}
}
}
}
//--------------------------------------------------------------------------
-------
//-----------------------------
Client1.cs ----------------------------------------
using System;
using SharedClasses;
namespace Client1
{
public class Client1
{
public Client1(){}

[STAThread]
static void Main(string[] args)
{
string strInput = "100";
SharedClass.Value = Convert.ToInt32(strInput);
Console.Write(SharedClass.Value);
Console.ReadLine();
}
}
}
//--------------------------------------------------------------------------
--------
//-----------------------------
Client2.cs ---------------------------------------

using System;
using SharedClasses;
namespace Client2
{
class Client2
{

[STAThread]
static void Main(string[] args)
{
Console.WriteLine(SharedClass.Value);
//I expected the output is 100, while Client1 is still running.
But it is not. Why?
//I want to get the value given by Client1. How can I do that?
Console.ReadLine();
}
}
}
//--------------------------------------------------------------------------
--------
 
D

Dmitriy Lapshin [C# / .NET MVP]

Hi,

This seems to be the expected behavior as each application owns a separate
application domain containing a single instance of the SharedClass. In other
words, declaring class as "static" means that it will have a single instance
per AppDomain, not per machine.

To overcome this, you will probably have to create a third AppDomain, load
an assembly containing the SharedClass into this domain, and talk to this
class across AppDomain boundaries. This will require some changes to the
SharedClass to support Remoting, though.

In this case, your shared data should live until the third AppDomain is shut
down.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top