Xamarin在等待的方法中加入

Xamarin在等待的方法中加入

问题描述:

在一个WPF应用程序中(F10),一个等待方法将把你带到下一行,但是在一个xamarin的android项目中,它并没有这样的行为(就好像我按了F5)为了正确调试,我们不得不在下一行放置一个断点 - 这是屁股的痛苦。Xamarin在等待的方法中加入

async Task SomeMethod() 
{ 
    await Task.Delay(1000); <--------- Stepping over this line leaves the function. 
    int x = 1; <--------- I have to add a breakpoint here. 
} 

它是一个错误或功能?

PS:我使用Visual Studio 2017

+4

Xamarin的尴尬调试经验通常是一个错误。当f11通常在单声道5出现之前工作时,通常会使调试器崩溃。如果我是你,我会在bugzilla.xamarin.com上报告。希望他们最终修复它。调试肯定是皮塔与普通的wpf应用程序相比 – Dbl

+0

它可能是'async'的一个特性 - 它只是在await操作的方法范围之外,并在后台继续。也许,你应该关闭**'Just My Code'复选框。 – VMAtm

这究竟是如何await运营商的作品。当您执行代码时,跳出当前函数并将控制权交给其调用者。然后在等待的Task完成后的某个时间点后,它会跳回到await声明后执行代码。

如果您跨过await,调试器将导航到您将要执行的下一行代码。在await的情况下,它很可能不会是以下行。

+4

请尝试在WPF,Windows窗体或Windows Phone中的代码,F10会带你到“int x = 1”,然后在Xamarin.Forms或Android中尝试它不会。 – Akli

确保您的方法处于异步。测试我的&它是从我身边工作。下面的示例: -

Task.Run(async() => 
     { 
     await Task.Delay(1000); 
     int x = 1; 
     }); 

async Task YourMethod 
    { 
     await Task.Delay(1000); 
     int x = 1; 
    } 
+0

你有什么版本的Visual Studio?它在Xamarin Droid中吗? – Akli

+0

适用于Mac的Visual Studio的最新版本是,它是Xamarin Droid。 –

这是不幸的是,怎样的Visual Studio调试当前工作。由于已经等待Task.Delay()方法,程序流程返回到调用YourMethod()的方法。如果这个调用正在等待,并且调用这个方法的调用链都等待回来,直到它到达应用程序上下文为止。例如。对于Xamarin:

例如

1 class MyActivity : Activity 
2 { 
3  // This function is called by the Xamarin/Android systems and is not awaited. 
4  // As it is marked as async, any awaited calls within will pause this function, 
5  // and the application will continue with the function that called this function, 
6  // returning to this function when the awaited call finishes. 
7  // This means the UI is not blocked and is responsive to the user. 
8  public async void OnCreate() 
9  { 
10   base.OnCreate(); 
11   await initialiseAsync(); // awaited - so will return to calling function 
12         // while waiting for operation to complete. 
13 
14   // Code here will run after initialiseAsync() has finished. 
15  } 
16  public async Task initialiseAsync() 
17  { 
18   await YourMethod(); // awaited - so will return to Line 11 
19        // while waiting for operation to complete. 
20   
21   // Code here will run after GetNamesAsync() has finished. 
22  } 
23 } 

在纯粹的Windows应用程序时,Visual Studio知道所有应用程序的快捷和知道的基本方法(程序生命周期,窗口事件,屏幕重绘等)不需要进行调试(和源代码无法访问)。你可能看到的是调试器暂停1000ms,因为没有代码需要调试。

Xamarin提供了额外的代码层,其中包括基类Activity类的实现和所有Android需求。 Visual Studio不知道跳过这些,因此试图调试任何称为当前等待的方法的代码。这可能类似于基类Activity类的OnCreate()方法 - 您可能无法访问该代码。