我经常看到建议用于异步库代码,我们应该ConfigureAwait(false)在所有异步调用上使用,以避免我们的调用返回将在UI线程或Web请求同步上下文上调度导致死锁等问题.
使用的一个问题ConfigureAwait(false)是,您不能在库调用的入口点上执行此操作.为了使其有效,必须在整个库代码中一直向下完成.
在我看来,一个可行的替代方案是在库的顶层面向公众的入口点简单地将当前同步上下文设置为null,然后忘掉ConfigureAwait(false).但是,我没有看到很多人采取或推荐这种方法.
简单地在库入口点上将当前同步上下文设置为null有什么问题吗?这种方法是否存在任何潜在的问题(除了将等待发布到默认同步上下文可能无关紧要的性能影响)?
(编辑#1)添加一些我的意思的示例代码:
public class Program
{
public static void Main(string[] args)
{
SynchronizationContext.SetSynchronizationContext(new LoggingSynchronizationContext(1));
Console.WriteLine("Executing library code that internally clears synchronization context");
//First try with clearing the context INSIDE the lib
RunTest(true).Wait();
//Here we again have the context intact
Console.WriteLine($"After First Call Context in Main Method is {SynchronizationContext.Current?.ToString()}");
Console.WriteLine("\nExecuting library code that does NOT internally clear the synchronization context");
RunTest(false).Wait();
//Here we again have the context intact
Console.WriteLine($"After Second Call Context …Run Code Online (Sandbox Code Playgroud) 甲java的 字符串包含特殊字符,如ç需要大小的两个字节中的每个特殊字符,但字符串长度的方法或得到的它的长度与字节数组从返回getBytes方法不返回计数为两个字节特殊字符.
如何正确计算字符串中的字节数?
例:
这个词endereço应该返回长度为9而不是8.