C# 我应该如何在 async/await 操作中使用静态方法/类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13046174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How should I use static method/classes within async/await operations?
提问by Patrick McCurley
It is my approach not to use static methods and classes within asynchronous operations - unless some locking technique is implemented to prevent race conditions.
我的方法是不在异步操作中使用静态方法和类 - 除非实现了一些锁定技术来防止竞争条件。
Now async/await has been introduced into the c# 4.5+ framework - which simplifies multithreaded applications and encourages responsive UI.
现在 async/await 已被引入到 c# 4.5+ 框架中——它简化了多线程应用程序并鼓励响应式 UI。
However - as a lock cannot/should not be placed over an awaiting method (and I'm not debating that) does that now make static methods utilizing async/await completely redundant?
但是 - 由于不能/不应该将锁放在等待方法上(我不是在争论这个),现在使用 async/await 的静态方法是否完全多余?
采纳答案by Jon Skeet
It is my approach not to use static methods and classes within asynchronous operations - unless some locking technique is implemented to prevent race conditions.
我的方法是不在异步操作中使用静态方法和类 - 除非实现了一些锁定技术来防止竞争条件。
Why? Unless you're actually using shared state, there shouldn't be any race conditions. For example, consider:
为什么?除非您实际上使用的是 shared state,否则不应该有任何竞争条件。例如,考虑:
public static async Task<int> GetPageLength(string url)
{
string text = await new WebClient().DownloadStringTaskAsync(url);
return text.Length;
}
If you dohave shared state - or if you're in an instancemethod on an instance which is used by multiple threads - you need to work out how you would ideally wantyour asynchronous operation to work. Once you've decided how the various races should behave, actually implementing it may well be fairly straightforward.
如果您确实有共享状态 - 或者如果您在多个线程使用的实例上的实例方法中 - 您需要确定理想情况下希望异步操作如何工作。一旦您决定了各种种族的行为方式,实际实施它可能相当简单。

