views:

79

answers:

1

I fear this is obvious, but would someone mind confirming that the private fields of WebServices are thread safe? Specifically,

1) In the code below, each thread will get a new instance of the ReportService class

protected void Page_Load(object sender, EventArgs e)
{
    // Client side scripting
    ScriptManager scriptManager = ScriptManager.GetCurrent(this);
    scriptManager.Services.Add(new ServiceReference("~/WebServices/ReportService.asmx"));
}

2) Because of (1), it is safe for each WebMethod in "ReportService" to manipulate and reference private fields as shown below:

[System.Web.Script.Services.ScriptService]
public class ReportService : : System.Web.Services.WebService
{
  private string _protocol = null;
  private string _reportType = null;

  [WebMethod]
  public string GetReport(string protocol, string reportType, string reportId)
  {
    _protocol = protocol;
    _reportType = reportType;
    return GetCustomReport(reportId);
  }
}

The methods above are dumbed down for the purposes of illustration. There is an example on MSDN using private fields, but the private field _xmlStr is not manipulated, leaving the question of thread safety ambiguous.

http://msdn.microsoft.com/en-us/library/bb398995.aspx

Thanks,

--Brett

+1  A: 

Yes this is thread safe but I would advice you to avoid using private fields in a web service. Just add the protocol and reportType parameters to the GetCustomReport method. This way you no longer need these fields.

Darin Dimitrov