C# 任务继续,等待返回错误
我有以下使用C# 任务继续,等待返回错误,c#,task-parallel-library,async-await,C#,Task Parallel Library,Async Await,我有以下使用System.Threading.Tasks private async void UploadDocument(System.IO.FileInfo fileInfo) { var someTask = await Task.Run<bool>(() => { // open input stream using (System.IO.FileStream stream = new System.IO.FileStr
System.Threading.Tasks
private async void UploadDocument(System.IO.FileInfo fileInfo)
{
var someTask = await Task.Run<bool>(() =>
{
// open input stream
using (System.IO.FileStream stream = new System.IO.FileStream(FileTextBox.Text, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
using (StreamWithProgress uploadStreamWithProgress = new StreamWithProgress(stream))
{
uploadStreamWithProgress.ProgressChanged += uploadStreamWithProgress_ProgressChanged;
// start service client
FileTransferWCF.FileTransferServiceClient client = new FileTransferWCF.FileTransferServiceClient();
//FileTransferClient.FileTransferServiceClient client = new FileTransferClient.FileTransferServiceClient();
// upload file
client.UploadFile(fileInfo.Name, fileInfo.Length, uploadStreamWithProgress);
// close service client
client.Close();
}
}
return true;
}).ContinueWith(r =>{
if(r.Result) LogText("Done!!");
});
}
private async void UploadDocument(System.IO.FileInfo)
{
var someTask=等待任务。运行(()=>
{
//开放输入流
使用(System.IO.FileStream stream=new System.IO.FileStream(FileTextBox.Text,System.IO.FileMode.Open,System.IO.FileAccess.Read))
{
使用(StreamWithProgress上载StreamWithProgress=新建StreamWithProgress(流))
{
uploadStreamWithProgress.ProgressChanged+=uploadStreamWithProgress\u ProgressChanged;
//启动服务客户端
FileTransferWCF.FileTransferServiceClient=新的FileTransferWCF.FileTransferServiceClient();
//FileTransferClient.FileTransferServiceClient=新建FileTransferClient.FileTransferServiceClient();
//上传文件
client.UploadFile(fileInfo.Name、fileInfo.Length、uploadStreamWithProgress);
//关闭服务客户端
client.Close();
}
}
返回true;
}).ContinueWith(r=>{
如果(r.Result)日志文本(“完成!!”);
});
}
如果我离开这个并尝试编译,我会得到:
“无法将void赋值给
var someTask
然后我将var someTask
更改为Task someTask
,但现在我得到了错误:
无法将类型“void”隐式转换为
“System.Threading.Tasks.Task”
有关于如何处理此问题的线索吗?关键字等待任务完成并返回结果 它不会返回任务本身 由于
ContinueWith()
没有结果(它返回Task
,而不是Task
),因此wait
表达式返回void
,这显然无法分配给变量
您可以这样简化代码:
await Task.Run(() => {
using (...) {
...
}
});
LogText("Done!");
wait
关键字等待任务完成并返回结果
它不会返回任务本身
由于ContinueWith()
没有结果(它返回Task
,而不是Task
),因此wait
表达式返回void
,这显然无法分配给变量
您可以这样简化代码:
await Task.Run(() => {
using (...) {
...
}
});
LogText("Done!");
好的,我可以去掉wait,但是我怎样才能使任务执行异步?@VAAA你是什么意思?SLaks并不是说你应该摆脱
await
,他是说你应该摆脱ContinueWith()
。好吧,我可以摆脱await,但是我怎样才能使任务异步执行?@VAAA你是什么意思?SLaks并不是说你应该摆脱await
,他是说你应该摆脱ContinueWith()
。你真的应该遵循Stephen在前面问题中的模型。这是设计这个系统的正确方法。正如我在那里评论的那样,日志甚至不应该首先出现在UploadDocument
中,它应该出现在调用者中。我应该用什么?我在你的链接中看到,只有在处理程序中void才是正确的,而我的则不是:(谢谢你真的应该遵循上一个问题中Stephen的模型。这是设计这个系统的正确方法。正如我在那里评论的那样,日志甚至不应该在UploadDocument
中,首先,它应该在调用者中。而不是:永远不要编写async void
。我应该使用什么?我在你的链接中看到void IIt’这只适用于处理程序,而我的则不适用