Thanks to both you guys, especially Nick.
Here is my code. I ran it with 3 clients calling the service in a loop
posting 1000 records each.
Before I put the .WriteLine method inside the mutex it would skip lines
or else write two numbers next to each other. Before I put the
increment of Register in the mutex it would skip or update to the same
number 2 or 3 times. With both inside the Mutex, it seems to work ok,
but I am going to load test further...
public class Service1 : System.Web.Services.WebService
{
public static int Register=5;
public static StreamWriter sw;
public static Mutex mut = new Mutex();
public Service1()
{
InitializeComponent();
}
[WebMethod]
public int Add1()
{
mut.WaitOne();
Register++;
sw.WriteLine(Register);
mut.ReleaseMutex();
return Register;
}
[WebMethod]
public void closeLog()
{
sw.Close();
}
[WebMethod]
public void openLog()
{
sw = new
StreamWriter("C:\\shareadd\\record.txt");
sw.AutoFlush=true;
}
}
Ken said:
As you said, every call to a web service is made on its own instance of
the
WebService class. But Nicholas has recommended you use a static field,
which
is shared by all instances of the web service. So, you would just create
a
static instance and use lock() to ensure thread-safe access to it.
Ken
Nicholas Paldino [.NET/C# MVP] wrote:
John,
You would create a static property in that case. As long as they
are in
the same app domain (and they should be), they should all hit the same
instance.
Are you saying that all clients access the same instance of a web
service -- and its associated methods ?
I thought that each call to a web service or web method instantiated a
new copy of the class ...