正确的C#5.0不能申请等待和异步 [英] Cannot apply Await and Async properly in C#5.0
问题描述
我有以下程序将从一个目录中的文件移动到其他。在sysnchronous方式,它的工作原理fine.But我想这样做,在异步方式。
I have the below program that will move files from one directory to other. In sysnchronous way, it works fine.But I want to do it in the asynchronous way.
感谢
推荐答案
错误说明了一切:你不能等待
的东西是无效
。您只能等待
任务
和东西,类似于任务
S(例如<一个href=\"http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.yieldawaitable%28v=vs.110%29.aspx\"相对=nofollow> YieldAwaitable
,这是通过的 Task.Yield()
)。但你肯定不能等待
无效
。
The error says it all: you can't await
something that is void
. You can only await
Task
s and things that look similar to Task
s (e.g. YieldAwaitable
, that's returned by Task.Yield()
). But you most certainly can't await
void
.
似乎没有要在.NET 4.5异步移动文件的方法。
There doesn't seem to be a way to asynchronously move a file in .Net 4.5.
你能做的最好是要么使用类似伺机Task.Run(()=&GT; fileinfo.MoveTo(目标))
,它仍然会阻止线程,而不是当前的(如果你是在UI线程可能是有用的)。
The best you can do is to either use something like await Task.Run(() => fileinfo.MoveTo(target))
, which will still block a thread, but not the current one (may be useful if you're on the UI thread).
或者,或者,你可以复制自己使用的文件流
S(可以是异步的),然后删除原始。
Or, alternatively, you could copy the file yourself using Stream
s (which can be asynchronous) and then delete the original.
这篇关于正确的C#5.0不能申请等待和异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!