2014-08-28 76 views
0

我希望创建一个异步任务,将从联机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#和异步/等待。任何帮助,将不胜感激!

+0

将其从公共更改为静态确实可以消除第一个错误。你是说* main *还必须标记为异步吗? – 2014-08-28 13:52:43

+0

谢谢!这固定了一切*迄今为止...... *! 干杯! – 2014-08-28 13:54:44

+0

很酷。我已将我的评论添加到答案中。 – 2014-08-28 13:56:47

回答

1

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 
} 
+0

你能否快速解释为什么'Main()'不应该是异步的?在你的例子中,我应该把'MainAsync()'作为我的'main()'并且从那里运行一切? 干杯! – 2014-08-29 00:49:12

+1

编译器不允许“异步Main”。原因是因为'async'方法在完成执行之前可以返回(即在'await'处)。如果'Main'返回,您的应用程序将退出。是的,你应该在'MainAsync'中做所有事情。 – 2014-08-29 00:52:17

+0

啊,欢呼声。我实际上并没有尝试编译'async Main',因为它迟到了,我直接上床睡觉! – 2014-08-29 01:08:04