[英]C# API - Calling ASync Task from another class
希望你一切都好,我正在用谷歌 API 做一些測試。我在 PHP 中的 API 知識相當不錯,但我在 C# 中努力做到這一點。我的目標是:
創建“JourneyPlanner”class 在其中調用 API 查詢以查找兩個郵政編碼之間的距離 打印距離
在 PHP 中相當簡單,但在 C# 中很難找到類似的方法。我可以從 Main 方法正常運行調用,但是當我嘗試實現新的 class 時,我遇到了一些問題。
我的 class 相當簡單:
public class JourneyDistance
{
private static readonly HttpClient client = new HttpClient();
public async static Task GetPostCodeDistance()
{
string postCodeOne = "NR116BN";
string postCodeTwo = "PE129JE";
string url;
url = $"https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins={postCodeOne}&destinations={postCodeTwo}&mode=driving&key=APIKEY";
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
var o = JObject.Parse(responseBody);
Console.WriteLine(o);
string child1 = (string)o["rows"][0]["elements"][0]["distance"]["text"];
Console.WriteLine(child1);
}
}
我在 Main 中嘗試了一些東西,但我不能簡單地運行有問題的方法,我的理由是我想在某個時候在系統中顯示和運行這個 API 調用,所以需要能夠每當我需要查詢兩個郵政編碼時調用此方法。
public class Program
{
private static readonly HttpClient client = new HttpClient();
static void Main(string[] args)
{
JourneyDistance journeyDistance = new JourneyDistance();
//await journeyDistance.GetPostCodeDistance();
//journeyDistance.GetPostCodeDistance();
}
}
有人可以幫忙嗎?
因為GetPostCodeDistance
是一種異步方法,它會在第一個await
被命中時返回一個Task
,將控制權交還給調用者。
此Task
將在GetPostCodeDistance
完成處理后完成,但您需要等待它完成,否則您的應用程序可能會過早退出。
在您的Main
方法中,您可以這樣做:
journeyDistance.GetPostCodeDistance().GetAwaiter().GetResult();
在Task
完成之前阻塞線程。
通常在調用異步方法時應避免阻塞線程,但頂級Main
方法是該規則的一個例外。
如果您使用的是 C#7.1+,您還可以使Main
方法異步:
static async Task Main(string[] args)
{
JourneyDistance journeyDistance = new JourneyDistance();
await journeyDistance.GetPostCodeDistance();
}
雖然這只是語法糖:
private static async Task MainAsync(string[] args)
{
JourneyDistance journeyDistance = new JourneyDistance();
await journeyDistance.GetPostCodeDistance();
}
public static void Main(string[] args)
=> MainAsync(args).GetAwaiter().GetResult();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.