TPL 异步静态方法调用线程安全
我需要对 WCF 服务进行四次异步调用,并且异步内容和静态方法的线程安全性总是让我费尽心思。
这四个对静态方法的异步调用应该是线程安全的,对吧?
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的 - 没有共享状态,因此不应该存在线程安全问题。 (编辑:正如评论中所指出的,假设可以同时从多个线程访问单独
SomeWcfClient
实例。它们必须写得很糟糕,否则会成为一个问题。)您可能会发现通道仅限于一次到同一主机/端口的两个连接,但这是一个单独的问题,仅影响并行性,而不影响线程安全。
顺便说一句,根本不清楚为什么您要在创建客户端之前声明返回变量,并为其分配一个永远不会使用的值。更简单的代码:
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: