0

I have a problem with an event that comes from other thread, I can't invoke my function in first Thread.

This is the code:

namespace Gestion_Photo_CM
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        GestionRecherche gRech = new GestionRecherche();
        Dispatcher disp = Dispatcher.CurrentDispatcher;

        public MainWindow()
        {
            InitializeComponent();
            gRech.evt_creer_objimage += afficherimage;
        }

        /// <summary>
        /// Affichage dynamique des images
        /// </summary>
        /// <param name="path"></param>
        public void afficherimage(Image obj)
        {
            if (disp.CheckAccess())
            {
                this.Dispatcher.Invoke(delegate () { afficherimage(obj); });
            }
            else
            {
                this.RootGrid.Children.Add(obj);
            }
        }

        /// <summary>
        /// Validation du chemin entré
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_valid_Click(object sender, RoutedEventArgs e)
        {
            string cheminDossier = tbfolderpath.Text;
            Thread thScanDossier = new Thread(delegate () { gRech.ScanDossiers(cheminDossier); });
            thScanDossier.SetApartmentState(ApartmentState.STA);
            thScanDossier.Start();
        }
    }
}

When the programme comes to this line:

this.RootGrid.Children.Add(obj);

An Exception says that it can't use the object because it is on another Thread.

Servy
  • 202,030
  • 26
  • 332
  • 449
C. MARTIN
  • 43
  • 12

1 Answers1

0

You've got your condition back to front. Per the documentation for Dispatcher.CheckAccess, it returns:

true if the calling thread is the thread associated with this Dispatcher; otherwise, false.

You need to call Invoke in the case it returns false:

if (this.Dispatcher.CheckAccess())
{
    this.RootGrid.Children.Add(obj);
}
else
{
    this.Dispatcher.Invoke(delegate () { afficherimage(obj); });
}

I'd also strongly suggest looking at Task.Run instead of working directly with Thread.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45