将此代码转换为任务以在另一个线程上异步运行 [英] Turn this code into a Task to run Asynchronously on another thread
问题描述
我开始玩Tasks并等待异步.为了更好地了解如何转换现有代码,我想尝试更改同步运行的当前方法:
I am starting to toy with Tasks and async await. So that I get a better handle on how to convert my existing code, I thought I would try to try changing a current method which is run synchronously:
private bool PutFile(FileStream source, string destRemoteFilename, bool overwrite)
{
if (string.IsNullOrEmpty(destRemoteFilename)) return false;
string path = Path.GetDirectoryName(destRemoteFilename);
if (path == null) return false;
if (!Directory.Exists(path)) Directory.CreateDirectory(path);
if (overwrite)
{
if (File.Exists(destRemoteFilename)) //delete file if it exists, because we are going to write a new one File.Delete(destRemoteFilename);
}
else if (File.Exists(destRemoteFilename)) return false;
using (FileStream dest = File.OpenWrite(destRemoteFilename))
{
source.Seek(0, SeekOrigin.Begin);
source.CopyTo(dest);
}
return true;
}
我试图将方法简单地更改为async
,并涉足了Task<bool>
,但是由于它们似乎都不起作用,我显然在这里缺少了一些东西.
我遇到了Type System.Threading.Task<bool>
不能等待的情况.
I have tried to simply change the method to async
, and dabbled with Task<bool>
but I'm obviously missing something here as neither of them seem to work.
I have experienced Type System.Threading.Task<bool>
is not awaitable.
推荐答案
您没有在方法中调用任何异步函数,因此首先将其标记为async
没有任何意义.但是,可以使用异步版本CopyToAsync
代替使用同步CopyTo
.
You're not calling any async functions in your method, so it would not make any sense to mark it async
in the first place. However instead of using the sync CopyTo
you can use the async version CopyToAsync
.
private static async Task<bool> PutFile(FileStream source, string destRemoteFilename, bool overwrite)
{
if(string.IsNullOrWhiteSpace(destRemoteFilename))
return false;
var path = Path.GetDirectoryName(destRemoteFilename);
if(path == null)
return false;
if(!Directory.Exists(path))
Directory.CreateDirectory(path);
if (overwrite)
if (!File.Exists(destRemoteFilename))
return false;
else
File.Delete(destRemoteFilename);
using (var dest = File.OpenWrite(destRemoteFilename))
{
source.Seek(0, SeekOrigin.Begin);
await source.CopyToAsync(dest);
return true;
}
}
..并且没有async/await:
.. And without async/await:
private static Task<bool> PutFile(FileStream source, string destRemoteFilename, bool overwrite)
{
if (string.IsNullOrWhiteSpace(destRemoteFilename))
return Task.Factory.StartNew(() => false);
var path = Path.GetDirectoryName(destRemoteFilename);
if(path == null)
return Task.Factory.StartNew(() => false);
if(!Directory.Exists(path))
Directory.CreateDirectory(path);
if (overwrite)
if (!File.Exists(destRemoteFilename))
return Task.Factory.StartNew(() => false);
else
File.Delete(destRemoteFilename);
using (var dest = File.OpenWrite(destRemoteFilename))
{
source.Seek(0, SeekOrigin.Begin);
return source.CopyToAsync(dest).ContinueWith(x => true);
}
}
这篇关于将此代码转换为任务以在另一个线程上异步运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!