我有以下类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());
}
}
}
}
下面是我的程序.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();
}
}
}
从 C# 7.1 开始,您可以使用异步主方法:
class Program
{
static async Task Main(string[] args)
{
GetProjectClass t = new GetProjectClass();
await t.GetProjects();
Console.WriteLine("finished");
Console.ReadKey();
}
}
在 C# 7.1 之前,这是不可能的.
注意:您需要更改GetProjects
以返回任务才能使其正常工作。