我希望创建一个异步任务,将从联机API请求数据。 我通过谷歌发现的所有资源并没有帮助我解决这个问题,因此我现在问。异步Web任务返回XML格式的字符串
到目前为止,程序很简单,包括:
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#和异步/等待。任何帮助,将不胜感激!
将其从公共更改为静态确实可以消除第一个错误。你是说* main *还必须标记为异步吗? – 2014-08-28 13:52:43
谢谢!这固定了一切*迄今为止...... *! 干杯! – 2014-08-28 13:54:44
很酷。我已将我的评论添加到答案中。 – 2014-08-28 13:56:47