[英]How do I make my application to run or wait until my “Task” completes?
我有下面的c#
代碼,其職責是從database
中獲取詳細信息並執行一些操作。
static void Main(string[] args)
{
try
{
ProcessTask().Wait();
}
catch (Exception ex)
{
Console.WriteLine($"There was an exception: {ex.ToString()}");
}
}
這是任務
static private async Task ProcessTask()
{
//Connect to database
//fetch data
//update data based on condition
}
但是我的程序在完成任務之前就出來了!
ProcessTask
中的一種方法正在等待“Connected”事件,因此 Task 假定它已完成。
最終目標:我想在 windows 調度程序中運行此代碼。 這樣我每隔一小時就可以檢查數據庫並進行更新。 所以我不能使用“console.readline()”
我假設您在控制台應用程序中進行此操作。 所以我建議做兩個改變。
static void Main(string[] args)
{
try
{
ProcessTask()
.GetAwaiter()
.GetResult(); // This will give you a better exception details compared to Task.Wait().
}
catch (Exception ex)
{
Console.WriteLine($"There was an exception: {ex.ToString()}");
#if DEBUG
Console.ReadLine(); // Generic error handler. Stop exiting. So you can read the exception.
#endif
}
}
嘗試這個
static async Task Main(string[] args)
{
try
{
await ProcessTask();
}
catch (Exception ex)
{
Console.WriteLine($"There was an exception: {ex.ToString()}");
}
}
像下面這樣
static void Main(string[] args)
{
callMethod();
Console.ReadKey();
}
public static async void callMethod()
{
Task<int> task = Method1();
int count = await task;
Method2(count);
}
// Do your db call here
public static async Task<int> Method1()
{
int count = 0;
await Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(" Method 1");
count += 1;
}
});
return count;
}
public static void Method2(int count)
{
Console.WriteLine("Total count is " + count);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.