异步等待同步混乱-恐怖 [英] Async Await Synchronous confusion - The Horror

查看:95
本文介绍了异步等待同步混乱-恐怖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在被这个驱动:(

所以我想写一个Metro App.撇开一个令人费解的事实,即已经淘汰了一半框架,有一件事我就是无法正确解决.

我想获取文件夹中的所有文件(实际上是递归的,但是那无关紧要),并且我想同步进行.我相信StorageFolder是该类,因为它代表一个文件夹.

现在,如果它具有GetFiles()方法,我会很高兴,但是取而代之的是GetFilesAsync().我要做的就是同步调用此方法.

现在,如果我调用它,它将立即返回,据我了解,异步调用在阻塞时的性质是.所以我可以等待它完成:

IReadOnlyList<StorageFile> f = await requestedFolder.GetFilesAsync();

但这意味着必须将调用方法标记为异步,并且只会将痛苦传播到它上面的方法.如此继续下去,为了等待方法完成,您需要等待",但这意味着使调用方异步等,直到整个应用程序变成一个庞大的异步汤为止.

考虑到异步方法返回Task,我已经尝试过Wait(),但这只会导致立即死锁(据我所知,在单个线程上-很好).

有任何想法吗?没有关于Google成为我朋友的明智答案-事实并非如此.在过去的5个小时中,我一直在恳求着它.

I AM BEING DRIVEN MAD BY THIS :(

So I''m trying to write a Metro App. Leaving aside the tiresome fact that half the framework has been ripped out, there is one thing which I just can''t get right.

I want to get all the files in a folder (recursively actually but that bit doesn''t matter) and I want to do it synchronously. I believe StorageFolder is the class for this as it represents a folder.

Now if it had a GetFiles() method I''d be happy, but instead its got GetFilesAsync(). All I want to do is call this method synchronously.

Now if I call this, it just returns immediately which I understand is the nature of async calls when they block. So I could await for it to finish:

IReadOnlyList<StorageFile> f = await requestedFolder.GetFilesAsync();

But that would mean having to mark the calling method as async and would just propagate the pain to the method above it. And so it goes on, in order to wait for a method to finish you need to ''await'' but that means making the caller async etc. etc. until the whole application has become one massive asynchronous soup.

Bearing in mind async methods return Tasks, I''ve tried Wait()ing on that but that just causes immediate deadlock (on a single thread from what I can tell - nice).

Any ideas? No smart answers about Google being my friend - it isn''t. I''ve been pleading with it for the last 5 hours for an answer.

推荐答案

您是否尝试过AsTask()扩展方法?这可能就是您所需要的.

签名:
WindowsRuntimeSystemExtensions.AsTask< tresult>方法(IAsyncOperation< tresult>)

MSDN链接
AsTask方法
Have you tried the AsTask() extenstion method? This may be what you need.

Signature:
WindowsRuntimeSystemExtensions.AsTask<tresult> Method (IAsyncOperation<tresult>)

MSDN Link
AsTask Method
var f = requestedFolder.GetFilesAsync().AsTask();

IReadOnlyList<storagefile> f = theTask.Result;


这篇关于异步等待同步混乱-恐怖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆