Debugging Xamarin跨过了一个等待的方法
在WPF应用程序中,一个等待的方法会将你带到下一行,但在xamarin android项目中,它不会这样做(就像我按了F5),我必须在下一行上设置一个断点,以便正确调试-这是一个麻烦Debugging Xamarin跨过了一个等待的方法,debugging,asynchronous,xamarin,xamarin.android,async-await,Debugging,Asynchronous,Xamarin,Xamarin.android,Async Await,在WPF应用程序中,一个等待的方法会将你带到下一行,但在xamarin android项目中,它不会这样做(就像我按了F5),我必须在下一行上设置一个断点,以便正确调试-这是一个麻烦 async Task SomeMethod() { await Task.Delay(1000); <--------- Stepping over this line leaves the function. int x = 1; <--------- I have to ad
async Task SomeMethod()
{
await Task.Delay(1000); <--------- Stepping over this line leaves the function.
int x = 1; <--------- I have to add a breakpoint here.
}
async Task SomeMethod()
{
等待任务。延迟(1000)这正是await
操作符的工作方式。当您await
aTask
时,代码执行将跳出当前函数并将控制权交给调用方。然后在等待的Task
完成后的某个时间点,它将在await
语句后跳回执行代码
如果您跨过一个wait
,调试器将引导您到下一行要执行的代码。如果是wait
,则很可能不会是下一行。确保您的方法是异步的。已测试我的方法&它正在从我这边工作。示例如下:-
Task.Run(async () =>
{
await Task.Delay(1000);
int x = 1;
});
或
不幸的是,这就是visual studio调试当前的工作方式。由于等待了Task.Delay()
方法,程序流返回到调用YourMethod()的方法
。如果该调用已被等待,以及对该方法的调用链,其中所有调用都在等待,以此类推,直到它到达应用程序上下文。例如,对于Xamarin:
e、 g
在纯windows应用程序中,Visual Studio了解应用程序的所有上下文,并且知道不需要调试底层方法(程序生命周期、窗口事件、屏幕重画等)(并且源代码无法访问)。您可能看到的是调试器暂停1000毫秒,因为没有要调试的代码
Xamarin添加了一层额外的代码,其中包括基本活动类的实现和所有Android需求。Visual Studio不知道跳过这些,因此尝试调试任何称为当前等待的方法堆栈的代码。这可能类似于基本活动class的OnCreate()
方法-您可能无法访问该方法的代码。请在WPF、Windows窗体或Windows Phone中尝试该代码,F10将带您访问“int x=1”,然后在Xamarin.Forms或Android中尝试。它不会。@voytasify wait不是这样工作的。wait将立即执行使用wait
关键字调用的方法,并在方法内执行代码。仅当在被调用的方法(或其被调用的方法)中调用其他(通常是I/O绑定)操作时,它们等待自己的结果(也可以使用await
调用方法或返回任务
),当前线程可能会被调度程序重新调整用途一段时间。因此,进入等待的方法应该总是有效的,跨过一个也应该有效。xamarin的笨拙调试体验通常是一个bug。Shift f11通常会在调试器正常工作时崩溃,直到mono 5出现。如果我是你,我会在bugzilla报告它.xamarin.com。希望他们最终能修复它。与普通wpf应用程序相比,调试确实是一个pita。它可能是异步
的一个功能-它只是超出了等待操作的方法范围,并在后台继续。也许,您应该关闭仅我的代码复选框。Visual Studio的哪个版本你有吗?它在Xamarin Droid中吗?是Visual Studio for Mac的最新版本&是的,它是Xamarin Droid。
async Task YourMethod
{
await Task.Delay(1000);
int x = 1;
}
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 }