我希望創建一個異步任務,將從聯機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