Question c# thread exception

Rafal1991

New member
Joined
Feb 12, 2023
Messages
4
Programming Experience
Beginner
If i set to list.ItemSource collection with i create in thread i get exception:
  th1 = new Thread(async() =>
            {
                System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
                ObservableCollection<Image> col = new ObservableCollection<Image>();
                List<string> listt = Directory.GetFiles("E:/anime").ToList();
                List<FileInfo> filee = new List<FileInfo>();



                foreach (string file in listt)
                {
                    filee.Add(new FileInfo(file));
                }
             
               
                    System.Diagnostics.Debug.WriteLine("Task1");
                col = await Copier.CopyFiles(filee, (x) => { });

                this.Dispatcher.Invoke(() =>
                {
                    Dispatcher.Invoke(() =>
                    {
                          list.ItemsSource= col;

                     
                    });
                 

                });
            });




            th1.SetApartmentState(ApartmentState.STA);
            th1.Start();
            th1.Join();


if set to list.itemsSource dynamic collection is work:
   System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);

            th1 = new Thread(async() =>
            {
                System.Diagnostics.Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
                ObservableCollection<Image> col = new ObservableCollection<Image>();
                List<string> listt = Directory.GetFiles("E:/anime").ToList();
                List<FileInfo> filee = new List<FileInfo>();



                foreach (string file in listt)
                {
                    filee.Add(new FileInfo(file));
                }
             
               
                    System.Diagnostics.Debug.WriteLine("Task1");
                col = await Copier.CopyFiles(filee, (x) => { });

                this.Dispatcher.Invoke(() =>
                {
                    Dispatcher.Invoke(() =>
                    {
                        list.ItemsSource = new ObservableCollection<Image> { new Image()};
                     

                     
                    });
                 

                });
            });




            th1.SetApartmentState(ApartmentState.STA);
            th1.Start();
            th1.Join();
         
         

        }
 
What exception are you getting?
 
What does CheckAccess() do? Is it called in the working version?

Anyway, it looks like you are comparing apples to oranges. In the non-working version, you are using whatever Copier.CopyFiles() returns, while in the working version you are using an ObservableCollection<Image> . It seems like the former has some kind of thread affinity.
 
Back
Top Bottom