Cannot apply Await and Async properly in C#5.0

a 夏天 提交于 2019-12-11 23:21:11

问题


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.

Thanks


回答1:


The error says it all: you can't await something that is void. You can only await Tasks and things that look similar to Tasks (e.g. YieldAwaitable, that's returned by Task.Yield()). But you most certainly can't await void.

There doesn't seem to be a way to asynchronously move a file in .Net 4.5.

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).

Or, alternatively, you could copy the file yourself using Streams (which can be asynchronous) and then delete the original.




回答2:


You can only use await when the method you are calling supports it.

To support await the method needs to return a Task<T>

In this case the fileInfo.MoveTo does not return a Task



来源:https://stackoverflow.com/questions/11167783/cannot-apply-await-and-async-properly-in-c5-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!