2

我试图让控制台应用程序调用Azure移动服务在数据库中执行插入操作(我试用的测试原型。我的最终目标是让控制台应用程序成为作为Azure webjob定期运行)。从控制台应用程序异步调用Azure移动服务

下面的代码片段做了一个插入。当我将Console.readline()注释掉时,程序会运行并退出,但什么也不做(无法插入)。当我有readline()时,它可以成功插入。我猜这是因为我调用了一个异步方法,并且即使在异步方法有机会完成之前,控件也仅仅流出了主体。

在我试图开发的最终应用程序中,控制台应用程序将开始漫长的更新操作,等待它完成,然后退出,直到天蓝色的web作业调度程序再次运行它。在这里完成“等待”的推荐方式是什么?

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(); 

    }   
} 

回答

3

在一个控制台应用程序,我建议你所有的实际逻辑(包括错误处理)的放置到一个MainAsync方法,然后调用Task.WaitMain,因为这样的:

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) 
    { 
     ... 
    } 
    } 
} 
+0

非常感谢你!这很好。 – user3233557

2
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"; 
    } 
} 

更多信息,可以发现here

+0

谢谢!我会试图弄清楚这是做什么,并试一试。 – user3233557

+0

这是做的事情是让你写正常的异步/等待模式。你需要这样做,因为你不能主要异步 –

2

它看起来像在控制台应用程序你真的想等待回应。在基于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(); 
    }   
} 
相关问题