C#。调用异步方法

时间:2014-03-21 18:59:06

标签: c# asynchronous task

我有异步方法:

public static async Task<HashSet<string>> getLinks(string page)
    {
        // GET request
        string str = await Client.get(page);

        // Pattern for http address
        Regex regx = new Regex(@"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?)", RegexOptions.IgnoreCase);
        str = str.Replace("&nbsp;", " ");

        // Get collection of strings
        MatchCollection matches = regx.Matches(str);

        // Add to the hash set
        HashSet<string> hashSet = new HashSet<string>();
        foreach (Match match in matches)
        {
            hashSet.Add(match.Value);
        }

        // Return set of url
        return hashSet;
    }

如何在不创建其他方法的情况下调用它?我试过这种方式:

HashSet<string> hashSet = new HashSet<string>();
hashSet = Client.getLinks("http://www." + textBox1.Text);

但得到了一个错误:Can not convert Task<HashSet<string>> to HashSet<string>.然后我尝试了:

hashSet = Client.getLinks("http://www." + textBox1.Text).Result;

但它不起作用。

1 个答案:

答案 0 :(得分:3)

使用await关键字:

hashSet = await Client.getLinks("http://www." + textBox1.Text);