异步Web任务返回XML格式的字符串

时间:2014-08-28 13:48:02

标签: c# asynchronous async-await task webclient

我希望创建一个异步任务,它将从在线API请求数据。 我通过谷歌找到的所有资源都没有帮助我解决这个问题,因此我现在就问。

到目前为止,该计划非常简单,包括:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Collections.Specialized;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello, world! Hit ANY key to continue...");
        Console.ReadLine();
        //Task<string> testgrrr = RunAsync();
        //string XMLString = await testgrrr;
        var XMLString = await RunAsync(); //The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
        //Some XML parsing stuff here
    }
}

public async Task<string> RunAsync()
{
    using (var client = new HttpClient())
    {
        var item = new List<KeyValuePair<string, string>>();
        item.Add(new KeyValuePair<string, string>("typeid", "34"));
        item.Add(new KeyValuePair<string, string>("usesystem", "30000142"));
        var content = new FormUrlEncodedContent(item);
        // HTTP POST
        response = await client.PostAsync("", content);
        if (response.IsSuccessStatusCode)
        {
            var data = await response.Content.ReadAsStringAsync();
            Console.WriteLine("Data:" + data);
            return data; //XML formatted string
        }
    }
    return "";
}

我希望能够让多个这些Web请求并行运行,并让它们返回要解析的XML String。该代码不适用于以下错误:

An object reference is required for the non-static field, method, or property 'EVE_API_TestApp.Program.RunAsync()'  
The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

我是C#和async / await的新手。任何有关这方面的帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

Main无法标记为async,因此您需要从Task.Wait致电Main。这是一般规则的罕见例外之一,您应该使用await而不是Wait

static void Main(string[] args)
{
  MainAsync().Wait();
}

static async Task MainAsync()
{
  Console.WriteLine("Hello, world! Hit ANY key to continue...");
  Console.ReadLine();
  var XMLString = await RunAsync();
  //Some XML parsing stuff here
}