异步/等待在调用方方法中不返回



我正在遵循这个来让异步/等待工作。

但是当我运行下面的代码作为调试时,它只打印

句柄文件输入

等。。。

然后继续跑,什么都不做,在我看来HandleFileAsync永远不会回来

public async Task  method1()
{
Task<int> task =  HandleFileAsync();    
log.Info("wait...");
task.Wait();
var x = task.Result;
log.Info("print x.."+ x);
}

static async Task<int> HandleFileAsync()
{
string file = @"C:Users....text.txt";
log.Info("HandleFile enter");
int count = 0;
// Read in the specified file.
// ... Use async StreamReader method.
using (StreamReader reader = new StreamReader(file))
{
string v = await reader.ReadToEndAsync();
// ... Process the file data somehow.
count += v.Length;
// ... A slow-running computation.
//     Dummy code.
for (int i = 0; i < 1000; i++)
{
int x = v.GetHashCode();
if (x == 0)
{
count--;
}
}  
}
log.Info("HandleFile exit");
return count;
}

如何让它运行以打印x

看看你分享的方法,async/await 看起来有点尴尬。

删除了第一个音符,并将空白改回任务。既然你在学习,这些事情就很重要。

第二个删除 task.wait 命令,使用 await。 请参阅我在下面所做的更改。

public async Task method1()
{
log.info('Starting process');
int task = await HandleFileAsync();    
log.Info("print x.."+ task);
}

我遇到了以下异步/等待入门。这篇博客文章与 Xamarin 相关,但它很好地解释了 async/await 模式。我希望它有所帮助。

最新更新