[英]Calling Azure mobile services asynchronously from a Console Application
我試圖讓一個控制台應用程序調用Azure移動服務以在數據庫中執行插入操作(我正在嘗試的測試原型。我的最終目標是讓控制台應用程序作為Azure Webjob定期運行)。
下面的代碼片段執行插入操作。 當我注釋掉Console.readline()時,程序只運行並退出但什么都不做(無法插入)。 當我在其中有readline()時,它可以成功插入。 我猜這是因為我正在調用異步方法,並且控制甚至在異步方法有機會完成之前就從主流中流出。
在我嘗試開發的最終應用程序中,控制台應用程序將啟動冗長的更新操作,等待其完成,然后退出,直到Azure Web Job Scheduler再次運行它為止。 在這里完成“等待”的推薦方法是什么?
class Program
{
static IMobileServiceTable<TodoItem> todoTable;
static void Main(string[] args)
{
MobileServiceClient MobileService = new MobileServiceClient(
"mymobileservice url",
"my application ID"
);
todoTable = MobileService.GetTable<TodoItem>();
todoTable.InsertAsync(new TodoItem() { Text = "Console Item 2", Complete = false });
//Console.ReadLine();
}
}
在Console應用程序中,我建議將所有實際邏輯(包括錯誤處理)放入MainAsync
方法,然后從Main
調用Task.Wait
,如下所示:
class Program
{
static IMobileServiceTable<TodoItem> todoTable;
static void Main(string[] args)
{
MainAsync(args).Wait();
}
static async Task MainAsync(string[] args)
{
try
{
MobileServiceClient MobileService = new MobileServiceClient(
"mymobileservice url",
"my application ID"
);
todoTable = MobileService.GetTable<TodoItem>();
await todoTable.InsertAsync(new TodoItem() { Text = "Console Item 2", Complete = false });
}
catch (Exception ex)
{
...
}
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting");
Task todo = asyncMethod();
todo.ContinueWith((str) =>
{
Console.WriteLine(str.Status.ToString());
Console.WriteLine("Main end");
});
todo.Wait();
}
public async static Task<string> asyncMethod()
{
MobileServiceClient MobileService = new MobileServiceClient(
"mymobileservice url",
"my application ID"
);
todoTable = MobileService.GetTable<TodoItem>();
await todoTable.InsertAsync(new TodoItem() { Text = "Console Item 2", Complete = false });
return "finished";
}
}
更多信息可以在這里找到。
在您的控制台應用程序中,您確實希望等待響應。 在基於UI的應用程序中,您不能真正地“等待”網絡操作完成,否則啟動它的線程(UI線程)將被阻止,並且應用程序將顯示為“掛起”。 但是在控制台上,您可以只詢問Task
的.Result
屬性(或調用.Wait()
),結果將是相同的:
class Program
{
static IMobileServiceTable<TodoItem> todoTable;
static void Main(string[] args)
{
MobileServiceClient MobileService = new MobileServiceClient(
"mymobileservice url",
"my application ID"
);
todoTable = MobileService.GetTable<TodoItem>();
var item = new TodoItem() { Text = "Console Item 2", Complete = false };
todoTable.InsertAsync(item).Wait();
var itemId = item.Id;
var retrieved = todoTable.LookupAsync(itemId).Result;
//Console.ReadLine();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.