WPF Cross Thread Object Access

后端 未结 3 1022
南旧
南旧 2021-01-24 04:34

I have an issue regarding cross thread calls in WPF.

            foreach (RadioButton r in StatusButtonList)
        {
            StatusType status = null;
             


        
相关标签:
3条回答
  • 2021-01-24 04:54
        r.Dispatcher.Invoke(
          System.Windows.Threading.DispatcherPriority.Normal,
          new Action(
            delegate()
            {
                    // DO YOUR If... ELSE STATEMNT HERE
            }
        ));
    
    0 讨论(0)
  • 2021-01-24 05:00

    I'd rewrite this to:

    r.Dispatcher.Invoke(new Action(delegate()
    {
        status = ((StatusButtonProperties)r.Tag).StatusInformation;
    
        if (AppLogic.CurrentStatus == null || AppLogic.CurrentStatus.IsStatusNextLogical(status.Code))
        {
            r.Background = Brushes.Green;
        }
        else
        {
            r.Background = Brushes.Red;
        }
    
    }));
    
    0 讨论(0)
  • 2021-01-24 05:05

    I am assuming that you are in a different thread than the one which created those RadioButtons. Otherwise the invoking makes no sense. Since you are creating the SolidColorBrush in that thread, you already have a potential cross-thread call there.

    It would make more sense to make the cross-thread calls more "chunky", i.e. put everything in the foreach loop in a single Invoke call.

    foreach (RadioButton r in StatusButtonList)
    {
        r.Dispatcher.Invoke(new ThreadStart(() => 
            {
                StatusType status = ((StatusButtonProperties)r.Tag).StatusInformation;
                if (AppLogic.CurrentStatus == null || AppLogic.CurrentStatus.IsStatusNextLogical(status.Code))
                {
                    SolidColorBrush green = new SolidColorBrush(Color.FromRgb(102, 255, 102));
                    r.Background = green;
                }
                else
                {
                    SolidColorBrush red = new SolidColorBrush(Color.FromRgb(255, 0, 0));
                    r.Background = red;
                }
            });
    }
    

    You could also consider using BeginInvoke if the different calls are not interdependant.

    0 讨论(0)
提交回复
热议问题