调试时应用程序不崩溃,但正常运行时崩溃

5

系统信息

  • Windows 10技术预览版(版本9926)
  • Visual Studio Community 2013

    尝试在以下设备上进行调试:
  • [AT&T] Lumia 635 (Windows 10手机技术预览版,版本9941,带有Lumia Cyan)
  • [AT&T] Lumia 1520 (Windows Phone 8.1,带有Lumia Denim和PfD)
  • [Unlocked] BLU Win Jr (Windows Phone 8.1,带有PfD)
  • [Verizon] Lumia Icon (Windows Phone 8.1,带有Lumia Denim和PfD)

我试图让我的应用程序能够使用位置服务。 以前,我在Visual Studio中出现了错误。 它是一个带有消息“Use of undefined keyword value 1 for event TaskScheduled in async”的ArgumentException。 搜索引擎没有提供任何解决方案。

这是我的代码:

Geolocator Locator = new Geolocator();
Geoposition Position = await Locator.GetGeopositionAsync();
Geocoordinate Coordinate = Position.Coordinate;

当我试图引发错误时,该异常会在上述示例的第二或第三行引发。

我简化了原始代码以尝试修复它,但以下是原始代码:

Geolocator Locator = new Geolocator();
Geocoordinate Coordinate = (await Locator.GetGeopositionAsync()).Position.Coordinate;

整个应用程序在调试时运行正常,但在其他情况下几乎立即崩溃。
这是一个以电话项目为重点的Windows 8.1通用项目。
提前致谢
编辑:按要求,以下是完整的方法:
private static bool CheckConnection()
{
    ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
    bool internet = connections != null && connections.GetNetworkConnectivityLevel() == NetworkConnectivityLevel.InternetAccess;
    return internet;
}
public static async Task<double> GetTemperature(bool Force)
{
    if (CheckConnection() || Force)
    {
        Geolocator Locator = new Geolocator();
        await Task.Yield(); //Error occurs here
        Geoposition Position = await Locator.GetGeopositionAsync();
        Geocoordinate Coordinate = Position.Coordinate;
        HttpClient Client = new HttpClient();
        double Temperature;
        Uri u = new Uri(string.Format("http://api.worldweatheronline.com/free/v1/weather.ashx?q={0},{1}&format=xml&num_of_days=1&date=today&cc=yes&key={2}",
                                      Coordinate.Point.Position.Latitude,
                                      Coordinate.Point.Position.Longitude,
                                      "API KEY"),
                                      UriKind.Absolute);
        string Raw = await Client.GetStringAsync(u);
        XElement main = XElement.Parse(Raw), current_condition, temp_c;
        current_condition = main.Element("current_condition");
        temp_c = current_condition.Element("temp_C");
        Temperature = Convert.ToDouble(temp_c.Value);
        switch (Memory.TempUnit)
        {
            case 0:
                Temperature = Convertions.Temperature.CelsiusToFahrenheit(Temperature);
                break;
            case 2:
                Temperature = Convertions.Temperature.CelsiusToKelvin(Temperature);
                break;
        }
        return Temperature;
    }
    else
    {
        throw new InvalidOperationException("Cannot connect to the weather server.");
    }
}

编辑2: 我已在Twitter上寻求帮助,并收到回复要求提供可重现项目。我重新创建了原始应用程序的主要部分,但我无法获得该错误。但是,您可能会遇到错误,因此这是该项目


编辑3: 如果有帮助的话,请看以下异常详情:

System.ArgumentException occurred
  _HResult=-2147024809
  _message=Use of undefined keyword value 1 for event TaskScheduled.
  HResult=-2147024809
  IsTransient=false
  Message=Use of undefined keyword value 1 for event TaskScheduled.
  Source=mscorlib
  StackTrace:
       at System.Diagnostics.Tracing.ManifestBuilder.GetKeywords(UInt64 keywords, String eventName)
  InnerException: 

@Noseratio 我已经尝试了你提供的两个线程中的所有方法。此外,我也尝试了你给出的解决方法。在调试时它仍然完美运行,但在非调试模式下仍然会崩溃。感谢你的回复。 - Greg Whatley
2
顺便说一句,我很欣赏你在这个年纪就能处理这么复杂的东西,干得好 :) - noseratio - open to work
@Noseratio 我使用了MessageDialogs来设置它,这些对话框会在Task.Yield()await Locator.GetGeopositionAsync()之后弹出。我猜测它在Task.Yield()处崩溃,因为没有任何对话框弹出。再次说明,只有在非调试状态下才会出现这种情况。顺便说一句,谢谢哈 :P - Greg Whatley
这段代码的home方法是什么,它是一个事件处理程序吗?你能编辑你的问题并展示一下吗? - noseratio - open to work
@Noseratio 我已经编辑了这个问题。 - Greg Whatley
显示剩余4条评论
1个回答

1

经检查thisthis,我认为这是WinRT的.NET async/await基础架构中的一个错误。虽然我无法重新制造出来,但我鼓励您尝试以下解决方法,看看是否有效。

  • Factor out all asynchronous awaitable calls from OnNavigatedTo into a separate async Task method, e.g. ContinueAsync:

    async Task ContinueAsync()
    {
        Geolocator Locator = new Geolocator();
        Geoposition Position = await Locator.GetGeopositionAsync();
        Geocoordinate Coordinate = Position.Coordinate; 
    
        // ...
    
        var messageDialog = new Windows.UI.Popups.MessageDialog("Hello");
        await messageDialog.ShowAsync();
    
        // ...
    }
    
  • Remove async modifier from OnNavigatedTo and call ContinueAsync from OnNavigatedTo like this:

    var scheduler = TaskScheduler.FromCurrentSynchronizationContext();
    Task.Factory.StartNew(
        () => ContinueAsync(), 
        CancellationToken.None, TaskCreationOptions.None, scheduler).
        Unwrap().
        ContinueWith(t => 
        {
            try
            {
                t.GetAwaiter().GetResult();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                throw; // re-throw or handle somehow
            }
        }, 
        CancellationToken.None,            
        TaskContinuationOptions.NotOnRanToCompletion, 
        scheduler);
    
请告诉我们是否有帮助 :)

更新: 显然,这个 bug 在 TPL 日志提供者 TplEtwProvider 中。如果你添加以下代码,你就可以看到它被创建了。到目前为止,我还没有找到一种方法来禁用这个事件源(无论是直接还是通过反射)。

internal class MyEventListener : EventListener
{
    protected override void OnEventSourceCreated(EventSource eventSource)
    {
        base.OnEventSourceCreated(eventSource);
        if (eventSource.Name == "System.Threading.Tasks.TplEventSource")
        {
            var enabled = eventSource.IsEnabled();

            // trying to disable - unsupported command :(
            System.Diagnostics.Tracing.EventSource.SendCommand(
                eventSource, EventCommand.Disable, new System.Collections.Generic.Dictionary<string, string>());
        }
    }
}

// ...
public sealed partial class App : Application
{
    static MyEventListener listener = new MyEventListener();
}

谢谢你的帮助,但我仍然无法让它工作。我不知道为什么会发生这种情况,我看到很多其他人也遇到了同样的问题。 - Greg Whatley
嗨,Greg - 我认为这是一个错误。我会提交它并在了解更多信息时更新您。我不能保证修复速度有多快。请在OneDrive上发布一个重现项目的链接,我将有东西转发给PG。 - Matt Small
@Noseratio,我已经添加了你提供的代码,并添加了一些Debug.WriteLine以查看输出:http://pastebin.com/7JxbvyeC - Greg Whatley
@GregWhatley,你可能想关注一下这个:https://dev59.com/SYfca4cB1Zd3GeqPnssr - noseratio - open to work
2
我会检查这个,但不会在下个星期之前更新,因为我要离开办公室。 - Matt Small
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接