我有以下课程GetProjectClass
,public static async void GetProjects()
我想调用这个方法/类,所以它对异步编程来说是“新的东西” - 目标是以实用的方式连接到TFS
我有以下代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class GetProjectClass
{
public static async void GetProjects()
{
try
{
var personalaccesstoken = "PAT_FROM_WEBSITE";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalaccesstoken))));
using (HttpResponseMessage response = client.GetAsync( "https://{account}.visualstudio.com/DefaultCollection/_apis/projects").Result)
{response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}
以下是我的program.cs文件,想要调用上面的内容,想知道这是否可能
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
GetProjectClass t = new GetProjectClass();
t.GetProjects().Wait();
Console.WriteLine("finished");
Console.ReadKey();
}
}
}
答案 0 :(得分:2)
从C# 7.1 you can use async main methods开始:
class Program
{
static async Task Main(string[] args)
{
GetProjectClass t = new GetProjectClass();
await t.GetProjects();
Console.WriteLine("finished");
Console.ReadKey();
}
}
预C#7.1这是不可能的。
注意:哟需要更改GetProjects
才能返回任务以使其正常运行。