这是我的代码。我使用异步void从Internet下载一些数据。我将此数据存储在名为“ Strona”的字符串变量中。我想在异步void之外使用“ Strona”的值。是否有可能以任何方式退还或获得使用权?
private async void starthttp()
{
string strona = "";
response = await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
var html = new HtmlDocument();
html.Load(response.GetResponseStream());
var nodes = html.DocumentNode.Descendants("img")
.Where(node => node.GetAttributeValue("alt", "")
.Equals("Celny")).ToList();
foreach (var node in nodes)
{
strona = strona + node.OuterHtml;
}
strona = strona.Replace('"', '\u0027');
strona = strona.Replace("< ", "<");
}
答案 0 :(得分:3)
Async
方法可以具有以下返回类型:
Task<TResult>
,用于返回值的异步方法。
Task
,用于执行操作但不返回任何值的异步方法
值。
void
,用于事件处理程序
在您的情况下,将Task<string>
用于返回字符串而不是void的任务
private async Task<string> starthttp()
{
string strona = "";
//your code stuff
return strona;
}
答案 1 :(得分:0)
草率的做法是声明全局变量,并在您的方法内部为其赋值,所以:
string stronaValue = "";
private async void starthttp()
{
string strona = "";
response = await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);
var html = new HtmlDocument();
html.Load(response.GetResponseStream());
var nodes = html.DocumentNode.Descendants("img")
.Where(node => node.GetAttributeValue("alt", "")
.Equals("Celny")).ToList();
foreach (var node in nodes)
{
strona = strona + node.OuterHtml;
}
strona = strona.Replace('"', '\u0027');
strona = strona.Replace("< ", "<");
stronaValue = strona;
}
但是我建议对Task使用上面的方法。