[英]How can I create a console application that utlilitize async/await
我正在創建一個氣象應用,該氣象應用會根據我提供的服務來查詢溫度:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Weather
{
class Program
{
static BackgroundWorker bgw;
static void Main(string[] args)
{
bgw = new BackgroundWorker();
bgw.DoWork += bgw_DoWork;
bgw.RunWorkerAsync();
}
static async void bgw_DoWork(object sender, DoWorkEventArgs e)
{
Weather bot = new Weather();
if (bot.IsRunning)
{
await bot.Update();
}
}
}
public class Weather
{
public bool IsRunning { get; set; }
private DateTime lastUpdated;
public Weather()
{
IsRunning = true;
lastUpdated = DateTime.Now.AddDays(-1);
}
public async Task<bool> Update()
{
if (lastUpdated < DateTime.Now)
{
lastUpdated = DateTime.Now.AddSeconds(30);
// temperature
double value = await GetLatestValue("New York");
}
return true;
}
private async Task<double> GetLatestValue(string city)
{
string url = "http://www" + city;
var client = new WebClient();
string data = await client.DownloadStringTaskAsync(url);
return 4.3;
}
}
}
這里的問題是它似乎不起作用? GetLatesValue函數只是一點點雜亂無章,僅返回4.3進行測試。
發生的情況是,在await GetLatestValue
,控制台應用程序剛剛退出。
這個問題比您想象的要簡單:您正在運行BackgroundWorker
,它基本上包裝了一個具有.IsBackground = true
的線程。 這樣的線程將無法使進程保持活動狀態-當進程退出時,它們將自動關閉。 所有非后台線程完成后,該過程將退出。
您的Main
方法將啟動BackgroundWorker
,但隨后不執行其他操作Main
退出,應用程序完成。 然后, BackgroundWorker
會在到達任何時候關閉。 它正在運行的代碼沒有任何問題-但該應用程序正在關閉而沒有完成。
編輯:如果您要測試此,只需在您的Main
的末尾放置一個Console.ReadLine()
-它可以使應用程序保持活動狀態,直到您按Enter鍵為止,因此您應該看到線程正在運行,直到您這樣做為止。
除了Dan Puzey的答案外 ,首先將async void
方法分配為BackgroundWorker
的事件處理程序沒有多大意義。
一旦執行點bgw_DoWork
內部的第一個await
位置,您的輔助方法bgw_DoWork
將返回並且后台線程將完成。 此時bot.Update
任務很可能仍將掛起。
您在這里不需要BackgroundWorker
。 代碼可以像這樣簡單:
static void Main(string[] args)
{
DoWorkAsync().Wait();
}
static async Task DoWorkAsync()
{
Weather bot = new Weather();
if (bot.IsRunning)
{
await bot.Update();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.