【问题标题】:Why my code wont work without Dispatcher.RunAsync in Geofencing [duplicate]为什么我的代码在地理围栏中没有 Dispatcher.RunAsync 时无法工作 [重复]
【发布时间】:2014-09-20 20:30:59
【问题描述】:

为什么没有 Dispatcher.RunAsync 这段代码不能工作,它有什么作用?如果没有 Dispatcher,它在将值复制到 textv.Text 时会抛出错误“那是它在不同的线程上”

     async void Current_GeofenceStateChanged(GeofenceMonitor sender, object args)
    {
        var reports = sender.ReadReports();

        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
        {
            foreach (var report in reports)
            {
                GeofenceState st = report.NewState;
                Geofence gf2 = report.Geofence;
                if (st == GeofenceState.Entered)
                {
                    textv2.Text = "Hello"; //XAML TEXT
                }
                else if(st==GeofenceState.Exited)
                {
                    textv2.Text = "Bye";
                }
            }
        });

    }

【问题讨论】:

    标签: c#


    【解决方案1】:

    事件Current_GeofenceStateChanged 在 GUI 线程之外触发,只有 GUI 线程可以更改 GUI 元素。 Dispatcher.RunAsync 说里面的代码应该在 GUI 线程上运行才能正常工作。

    如果你把结果放在一个字符串变量上,如果你只放:

      Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => textv2.Text = StringVariable;);
    

    编辑:我只注意到稍后您有 XAML 代码,您可以将字符串放在属性上并将属性绑定到文本框的文本值,让您从 Dispatcher 中解放出来。

    <TextBox Text="{Binding StringVariable}"/>
    

    并且在代码上只有

    public string StringVariable { get; set; }
    

    在方法上只是将值设置为属性

    StringVariable = "bla bla";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 2019-08-14
      • 2019-01-28
      • 1970-01-01
      • 2011-12-14
      • 2016-04-09
      相关资源
      最近更新 更多