25 April 2020

WPF update user interface in multithreading mode

   public partial class Window1 : Window  
   {  
     public Class1 c;  
     public Window1()  
     {  
       InitializeComponent();  
       c = new Class1();  
       c.Class1Event += C_Class1Event;  
      }  
     private void C_Class1Event(object sender, Class1EventArgs e)  
     {//Triggered from a different thread  

       this.Dispatcher.Invoke((Action)(() =>  
       {//this refer to form in WPF application   
         imgShirt.Source = new BitmapImage(new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"\images2.jpg", UriKind.RelativeOrAbsolute));  
       }));  

     }  
     private void Change_Click(object sender, RoutedEventArgs e)  
     {  
       c.Start();  
     }  
     private void Change2_Click(object sender, RoutedEventArgs e)  
     {//Called from the same thread  
       Uri fileUri = new Uri(System.AppDomain.CurrentDomain.BaseDirectory + @"\images.jpg", UriKind.RelativeOrAbsolute);  
       imgShirt.Source = new BitmapImage(fileUri);  
     }  
   }  
   public class Class1  
   {  
     public event EventHandler<Class1EventArgs> Class1Event;  
     public Class1()  
     {  
     }  
     public void Start()  
     {  
       Task.Run(() => {  
         Class1EventArgs e = new Class1EventArgs();  
         Class1Event(this, e);  
       });  
     }  
   }  
   public class Class1EventArgs : EventArgs  
   {  
   }  

1 comment: