开发者

TPL Asynchronous Static Method Call Thread Safety

I need to make four calls to a WCF service asynchronously and thread safety with async stuff and static methods always cooks my brain.

These four async calls to the static method should be thread safe right?

    private void CheckStuff()
    {
        bool? res1, res2, res3, res4;

        // make 4 async calls to SomeServiceCall and wait for all
        Task[] tasks = new Task[]
                            {
                                Task.Factory.StartNew(() => res1 = SomeServiceCall("apple")),
开发者_开发技巧                                Task.Factory.StartNew(() => res2 = SomeServiceCall("orange")),
                                Task.Factory.StartNew(() => res3 = SomeServiceCall("apple")),
                                Task.Factory.StartNew(() => res4 = SomeServiceCall("banana"))
                            };
        Task.WaitAll(tasks);
    }

    private static bool? SomeServiceCall(string someParam)
    {
        bool? retVal = null;

        var client = new SomeWcfClient();

        retVal = client.CheckSomething(someParam);

        return retVal;
    }


Yes - there's no shared state, so there should be no thread-safety issues. (EDIT: As noted in comments, that's assuming that it's okay to access separate SomeWcfClient instances from multiple threads concurrently. They would have to be poorly written for that to be a problem.)

You may find that the channel is limited to two connections to the same host/port at a time, but that's a separate matter and only affects the parallelism, not the thread safety.

As an aside, it's not at all clear why you'd want to declare the return variable before creating the client, and assign it a value which will never be used. Simpler code:

private static bool? SomeServiceCall(string someParam)
{
    var client = new SomeWcfClient();
    return client.CheckSomething(someParam);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜