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

本文关键字:格式 字符串 XML 返回 web 任务 异步 | 更新日期: 2023-09-27 18:19:55

我希望创建一个异步任务,该任务将从在线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字符串。代码无法工作,出现以下错误:

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的新手。如有任何帮助,我们将不胜感激!

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

Main不能标记为async,因此您需要从Main调用Task.Wait。对于应该使用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
}