c# - 应用程序在调试时不会崩溃,但在正常运行时会崩溃

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

System Information

  • Windows 10 Technical Preview (build 9926)
  • Visual Studio Community 2013

    Attempting to debug on:
  • [AT&T] Lumia 635 (Windows 10 Technical Preview for phones build 9941 w/ Lumia Cyan)
  • [AT&T] Lumia 1520 (Windows Phone 8.1 with Lumia Denim and PfD)
  • [Unlocked] BLU Win Jr (Windows Phone 8.1 with PfD)
  • [Verizon] Lumia Icon (Windows Phone 8.1 with Lumia Denim and PfD)

我试图让定位服务在我的应用程序中运行。以前,我让 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 Twitter , 和 received 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: 

最佳答案

检查了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();
    
        // ...
    }
    
  • OnNavigatedTo 中删除 async 修饰符并从 OnNavigatedTo 中调用 ContinueAsync,如下所示:

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

关于c# - 应用程序在调试时不会崩溃,但在正常运行时会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28269415/

相关文章:

c# - C# 应用程序中的管理员权限提示弹出窗口

c# - 具有嵌套对象的构建器模式

C# Silverlight 3 - 以编程方式在页面之间导航?

c# - 为什么我需要在 SaveChanges 之前更改 Binding Source Position

Flutter:如何获得高精度定位?

rust - tokio是多线程的吗?

c# - httpclient async/await 与否

java - 支持空间查询的内存数据库

javascript - 如何使用 JavaScript 在 HTML 中显示当前国家和城市

javascript - 在自定义 promise 上使用异步等待