[英]C# Async method usage
I am trying to use Aync method. 我正在尝试使用Aync方法。 It's working in a way. 它在某种程度上起作用。 But it's not working in some other context. 但它不适用于其他一些环境。
Working example 工作实例
dropBox.DownloadFileAsync(csvEntry.Path)
.ContinueWith(task =>
{
// Save file to "C:\Spring Social.txt"
using (FileStream fileStream = new FileStream(tempCsvPath, FileMode.Create))
{
fileStream.Write(task.Result.Content, 0, task.Result.Content.Length);
}
});
Instead of saving the file, I am trying to return the byte array in the following way. 我试图以下列方式返回字节数组,而不是保存文件。 But it's not working. 但它不起作用。 It is returning null. 它返回null。
byte[] returnArray = null;
dropbox.DownloadFileAsync(filePath)
.ContinueWith(task =>
{
returnArray = new byte[task.Result.Content.Length];
task.Result.Content.CopyTo(returnArray, 0);
});
return returnArray;
Can somebody correct me? 有人可以纠正我吗?
Thanks 谢谢
In this code: 在这段代码中:
byte[] returnArray = null;
dropbox.DownloadFileAsync(filePath)
.ContinueWith(task =>
{
returnArray = new byte[task.Result.Content.Length];
task.Result.Content.CopyTo(returnArray, 0);
});
return returnArray;
DownloadFileAsync() is executed on a thread. DownloadFileAsync()在线程上执行。 When the ContinueWith() is executed your function that calls DowloadFileAsync() already has returned. 当执行ContinueWith()时,调用DowloadFileAsync()的函数已经返回。
You would need to do something like this: 你需要做这样的事情:
Task<T> Download(string filePath)
{
return dropbox.DownloadFileAsync(filePath)
.ContinueWith(task =>
{
returnArray = new byte[task.Result.Content.Length];
task.Result.Content.CopyTo(returnArray, 0);
return returnArray;
});
}
Call it like this: 像这样称呼它:
var task = Download("myfile");
task.ContinueWith(t =>
{
var returnArray = t.Result;
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.