应用程序在调试时不会崩溃,但在正常运行时会出现问题

时间:2015-02-02 00:02:00

标签: c# geolocation async-await win-universal-app argumentexception

  

系统信息

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

    尝试调试:
  •   
  • [AT& T] Lumia 635(适用于手机的Windows 10技术预览构建了9941带Lumia Cyan)
  •   
  • [AT& T] Lumia 1520(带有Lumia Denim和PfD的Windows Phone 8.1)
  •   
  • [Unlocked] BLU Win Jr(带有PfD的Windows Phone 8.1)
  •   
  • [Verizon] Lumia Icon(带有Lumia Denim和PfD的Windows Phone 8.1)
  •   

我尝试在我的应用中使用位置服务。以前,我有Visual Studio抛出错误。这是ArgumentException,其中包含消息" Use of undefined keyword value 1 for event TaskScheduled in async"。谷歌搜索没有找到任何解决方案。

以下是代码:

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

当我可以抛出错误时,在上面的示例中的第2行或第3行抛出了异常。 我简化了原始代码以尝试修复它,但这是原始代码:

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

整个应用程序在调试时都能正常工作,但几乎瞬间崩溃。

这是一个Windows 8.1 Universal项目,专注于手机项目。

提前致谢


编辑:根据要求,这是完整的方法:

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:asked for help on Twitterreceived a reply要求重新投放项目。我重新创建了原始应用程序的主要部分,但我无法得到错误。但是,您可能会发生错误so here's the project


编辑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: 

1 个答案:

答案 0 :(得分:1)

检查了thisthis后,我认为这是.NET async/await infrastructure for WinRT中的错误。我无法重复它,但我鼓励您尝试以下解决方法,看看它是否适合您。

  • 将所有异步等待的来电从OnNavigatedTo分解为单独的async Task方法,例如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();
    
        // ...
    }
    
  • async移除OnNavigatedTo修饰符并从ContinueAsync拨打OnNavigatedTo,如下所示:

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

请告诉我们是否有帮助:)


已更新,显然,该错误位于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();
}