【发布时间】:2014-05-16 15:19:28
【问题描述】:
我想写以下内容:
public string GetSomeValue()
{
//directly return the value of the Method 'DoSomeHeavyWork'...
var t = DoSomeHeavyWork();
return t.Result;
}
public Task<string> DoSomeHeavyWork()
{
return Task.Run(() => {
// do some long working progress and return a string
return "Hello World!";
});
}
如您所见,从 DoSomeHeavyWork() 返回结果我使用了 Task.Result 属性,它工作正常,但根据研究,这将阻塞线程。
我想为此使用异步/等待模式,但似乎找不到如何做到这一点。 如果我用我目前的知识对 async/await 做同样的事情,我总是会得到这样的结果:
public async Task<string> GetSomeValue()
{
//directly return the value of the Method 'DoSomeHeavyWork'...
var t = DoSomeHeavyWork();
return await t;
}
public Task<string> DoSomeHeavyWork()
{
return Task.Run(() => {
// do some long working progress and return a string
return "Hello World!";
});
}
这个解决方案不太符合我的需求,因为我只想返回字符串而不是 Task<string>,如何通过 async/await 来实现?
【问题讨论】:
-
你为什么不能返回
Task<string>,因为当你await它返回一个string。这不是你想要的吗?
标签: c# multithreading asynchronous