WPF Cross Thread Object Access

后端 未结 3 1064
南旧
南旧 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 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.

提交回复
热议问题