相关疑难解决方法(0)

为什么从Async CTP/Release中删除"SwitchTo"?

我今天尝试使用SwitchTo方法切换到GUI线程,并发现我解除它的示例不起作用,仅仅是因为该方法不存在.

然后我在这里发现了这个模糊:

我们摆脱它的原因是因为它太危险了.另一种方法是在TaskEx.Run中捆绑你的代码......

我的问题很简单:为什么它很危险?使用它会带来哪些特定的危险?

请注意,我确实阅读了该帖子的其余部分,因此我确实理解这里存在技术限制.我的问题仍然是,如果我意识到这一点,为什么它很危险

我正在考虑重新实现帮助方法来给我指定的功能,但如果有一些根本性的破坏,除了有人认为它是危险的,我不会这样做.

具体来说,非常天真,这是我如何考虑实现所需的方法:

public static class ContextSwitcher
{
    public static ThreadPoolContextSwitcher SwitchToThreadPool()
    {
        return new ThreadPoolContextSwitcher();
    }

    public static SynchronizationContextSwitcher SwitchTo(this SynchronizationContext synchronizationContext)
    {
        return new SynchronizationContextSwitcher(synchronizationContext);
    }
}

public class SynchronizationContextSwitcher : INotifyCompletion
{
    private readonly SynchronizationContext _SynchronizationContext;

    public SynchronizationContextSwitcher(SynchronizationContext synchronizationContext)
    {
        _SynchronizationContext = synchronizationContext;
    }

    public SynchronizationContextSwitcher GetAwaiter()
    {
        return this;
    }

    public bool IsCompleted
    {
        get
        {
            return false;
        }
    }

    public void OnCompleted(Action action) …
Run Code Online (Sandbox Code Playgroud)

c# asynchronous async-await async-ctp

13
推荐指数
2
解决办法
1114
查看次数

为什么 File.ReadAllLinesAsync() 会阻塞 UI 线程?

这是我的代码。读取文件行的​​ WPF 按钮的事件处理程序:

private async void Button_OnClick(object sender, RoutedEventArgs e)
{
    Button.Content = "Loading...";
    var lines = await File.ReadAllLinesAsync(@"D:\temp.txt"); //Why blocking UI Thread???
    Button.Content = "Show"; //Reset Button text
}
Run Code Online (Sandbox Code Playgroud)

File.ReadAllLines()在 .NET Core 3.1 WPF App 中使用了异步版本的方法。

但它阻塞了 UI 线程!为什么?


更新:与@Theodor Zoulias 相同,我做了一个测试:

private async void Button_OnClick(object sender, RoutedEventArgs e)
    {
        Button.Content = "Loading...";
        TextBox.Text = "";

        var stopwatch = Stopwatch.StartNew();
        var task = File.ReadAllLinesAsync(@"D:\temp.txt"); //Problem
        var duration1 = stopwatch.ElapsedMilliseconds;
        var isCompleted = task.IsCompleted;
        stopwatch.Restart();
        var lines …
Run Code Online (Sandbox Code Playgroud)

c# wpf asynchronous async-await .net-core-3.1

4
推荐指数
1
解决办法
620
查看次数

标签 统计

async-await ×2

asynchronous ×2

c# ×2

.net-core-3.1 ×1

async-ctp ×1

wpf ×1