猿问

如何访问放置在该 void 之外的 async void 中的字符串值

这是我的代码。我使用 async void 从 Internet 下载一些数据。我将此数据存储在名为“Strona”的字符串变量中。我想在异步无效之外使用“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("< ", "<");

}


拉莫斯之舞
浏览 153回答 2
2回答

暮色呼如

Async&nbsp;方法可以具有以下返回类型:Task<TResult>, 用于返回值的异步方法。Task, 用于执行操作但不返回任何值的异步方法。void, 对于事件处理程序在您的情况下,Task<string>用于返回字符串而不是 void 的任务private async Task<string> starthttp(){&nbsp; &nbsp; string strona = "";&nbsp; &nbsp; //your code stuff&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; return strona;}

沧海一幻觉

草率的做法是声明全局变量并在您的方法中为其赋值,所以:string stronaValue = "";&nbsp; &nbsp; private async void starthttp(){&nbsp; &nbsp; string strona = "";&nbsp; &nbsp; response = await Task.Factory.FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, null);&nbsp; &nbsp; var html = new HtmlDocument();&nbsp; &nbsp; html.Load(response.GetResponseStream());&nbsp; &nbsp; var nodes = html.DocumentNode.Descendants("img")&nbsp; &nbsp; &nbsp; &nbsp; .Where(node => node.GetAttributeValue("alt", "")&nbsp; &nbsp; &nbsp; &nbsp; .Equals("Celny")).ToList();&nbsp; &nbsp; foreach (var node in nodes)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; strona = strona + node.OuterHtml;&nbsp; &nbsp; }&nbsp; &nbsp; strona = strona.Replace('"', '\u0027');&nbsp; &nbsp; strona = strona.Replace("< ", "<");&nbsp; &nbsp; stronaValue = strona;}但是,我建议将上述方法与 Task 一起使用。
随时随地看视频慕课网APP
我要回答