0

I am wondering if the following code is thread safe?

Can i be be sure that UniqueFoo will indeed be the Unique Foo and will not be override?

public partial class Dummy : System.Web.UI.Page
{
    public string UniqueFoo{ get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        var id = int.Parse(Request["Id"]);
        UniqueFoo = SomeThreadSafeWCF.GetUniqueFoo(id);
    }
}

what about the following (static)

public partial class Dummy : System.Web.UI.Page
{
    public static string UniqueFoo{ get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        var id = int.Parse(Request["Id"]);
        UniqueFoo = SomeThreadSafeWCF.GetUniqueFoo(id);
    }
}

i later want to use UniqueFoo in a [WebMethod]

[WebMethod]
public static void SetSomeObject(SetSomeObject obj)
{
    SomeThreadSafeWCF service = new SomeThreadSafeWCF ();
    service.SetSomeObject(UniqueFoo, obj);
}

EDIT: I am getting SetSomeObject from JS and UniqueFoo is coming from ASP.NET will i have any issues when NOT using the static in my Dummy class according to your answers?

4

2 回答 2

1

Surely your first sample is thread safe because when a request of a page post to the Web Server asp.net make new instance of your page and call page_load so if your SomeThreadSafeWCF.GetUniqueFoo() always make a unique Foo everything is thread save

于 2013-01-24T09:34:09.137 回答
0

您的第二个代码片段不是线程安全的,因为您正在修改静态字段的值。因此,例如,如果稍后在此页面中您尝试读取此UniqueFoo字段的值,您可能无法获得您期望的值。

第一个代码片段很好,因为该字段不是静态的。

如果您想在 WebMethod 中使用 UniqueFoo,那么我建议您在调用它时将其传递给此 Web 方法。

[WebMethod]
public static void SetSomeObject(SetSomeObject obj, string uniqueFoo)
{
    SomeThreadSafeWCF service = new SomeThreadSafeWCF ();
    service.SetSomeObject(uniqueFoo, obj);
}
于 2013-01-24T09:26:29.623 回答