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

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,消息“在异步中使用未定义的关键字值1为事件TaskScheduled”.谷歌搜索没有找到任何解决方案.

这是代码:

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: 
最佳答案
检查了thisthis后,我相信这是.NET async/await infrastructure for WinRT中的一个错误.我无法重复它,但我鼓励您尝试以下解决方法,看看它是否适合您.

>将OnNavigatedTo中的所有异步等待调用分解为单独的异步任务方法,例如: 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中的某个位置.如果添加以下代码,可以看到它已创建.到目前为止,我找不到禁用此事件源的方法(直接或通过Reflection):

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# – 应用程序在调试时不会崩溃,但在正常运行时会出现问题 - 代码日志