小编dta*_*enc的帖子

ConfigureAwait(false)vs将同步上下文设置为null

我经常看到建议用于异步库代码,我们应该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)

c# task-parallel-library async-await

10
推荐指数
1
解决办法
1546
查看次数

如何正确计算字符串字节数?

包含特殊字符,如ç需要大小的两个字节中的每个特殊字符,但字符串长度的方法或得到的它的长度与字节数组从返回getBytes方法不返回计数为两个字节特殊字符.

如何正确计算字符串中的字节数?

例:

这个词endereço应该返回长度为9而不是8.

java string encoding utf-8

3
推荐指数
1
解决办法
2634
查看次数

标签 统计

async-await ×1

c# ×1

encoding ×1

java ×1

string ×1

task-parallel-library ×1

utf-8 ×1