【问题标题】:Task ContinuewWith await returning error任务 ContiuewWith 等待返回错误
【发布时间】:2023-03-13 00:05:01
【问题描述】:

我有以下使用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!!");
    });

}

如果我离开这个并尝试编译,我会得到:

“不能将 void 分配给隐式类型的局部变量”** 在 var someTask

然后我将var someTask 更改为Task someTask 但现在我收到错误:

"不能将类型 'void' 隐式转换为 'System.Threading.Tasks.Task'”。

关于如何处理这个问题的任何线索?

【问题讨论】:

  • 您确实应该遵循上一个问题中斯蒂芬的模型。这是设计这个系统的正确方法。正如我在那里评论的那样,日志记录甚至不应该在 UploadDocument 中,它应该在调用者中。
  • 旁白:永远不要写async void。 blogs.msdn.com/b/lucian/archive/2013/02/18/…
  • 我应该使用什么?我在您的链接中看到 void 仅在处理程序中是可以的,而我的不是:( 谢谢

标签: c# task-parallel-library async-await


【解决方案1】:

await 关键字等待任务完成并返回结果。

它不返回任务本身。

由于您的ContinueWith() 没有结果(它返回Task,而不是Task&lt;T&gt;),因此您的await 表达式返回void,显然不能将其分配给变量。

你可以像这样简化你的代码:

await Task.Run(() => {
    using (...) {
        ...
    }
});
LogText("Done!");

【讨论】:

  • 好的,我可以摆脱等待,但是我怎样才能让任务异步执行?
  • @VAAA 你是什么意思? SLaks 并不是说​​你应该摆脱await,他是说你应该摆脱ContinueWith()。
猜你喜欢
  • 2014-10-01
  • 2017-06-02
  • 1970-01-01
  • 1970-01-01
  • 2013-08-06
  • 2016-09-10
  • 1970-01-01
  • 2017-06-13
相关资源
最近更新 更多