-1

I'm working on a C# WinForms project.

I try to work with multi threading in a part of my App :

Part code (Method) :

public void ShowData()
{
    Thread t;
    t = new Thread(() =>
      {

          using (GVentesEntities context = new GVentesEntities())
          {
              dataGridView1.DataSource = (from F in context.Facture.AsEnumerable() join C in context.Client.AsEnumerable() on F.CLT equals C.ID select new { ID = F.ID, F.Date, Client = $"{C.Nom} {C.Prenom}", Total = $"{(from df in context.Det_Fact.AsEnumerable() join cmd in context.Commande.AsEnumerable() on df.CMD equals cmd.ID where df.FACT == F.ID select cmd.QTE * cmd.PRU).Sum():00} MAD" }).OrderBy(x => int.Parse($"{x.ID.Substring(x.ID.IndexOf("-") + 1)}")).ToList();
          }

      });

    Thread.Sleep(1000);
    t.Start();
}

The problem is when I try to access this method when application is run I get an error :

Error

System.InvalidOperationException: 'Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.'

Please any help to handle this problem and execute my method with threading ? thanks in advance.

X Dev
  • 97
  • 1
  • 9
  • Perhaps instead you should be using a System.Threading.Tasks.Task? https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task.run?view=netcore-3.1 – 230Daniel Nov 02 '20 at 11:15
  • This answer didn't help, please I need a practical and clearly solution, after your permission sir and massive thanks for your time – X Dev Nov 02 '20 at 11:26
  • This isn't an answer it's a comment. Please could you provide more information about what you're trying to achieve? Are you trying to perform an action in the background while keeping your UI unfrozen? Edit: Nevermind is dupe – 230Daniel Nov 02 '20 at 12:05

1 Answers1

1

You need to bind back on the UI thread - e.g.

var values = (from F in context.Facture.AsEnumerable() join C in context.Client.AsEnumerable() on F.CLT equals C.ID select new { ID = F.ID, F.Date, Client = $"{C.Nom} {C.Prenom}", Total = $"{(from df in context.Det_Fact.AsEnumerable() join cmd in context.Commande.AsEnumerable() on df.CMD equals cmd.ID where df.FACT == F.ID select cmd.QTE * cmd.PRU).Sum():00} MAD" }).OrderBy(x => int.Parse($"{x.ID.Substring(x.ID.IndexOf("-") + 1)}")).ToList();

this.Invoke(new Action(() => this.dataGridView1.DataSource = values));
NDJ
  • 5,189
  • 1
  • 18
  • 27
  • Massive thanks sir this is very helpful answer, Please sir do you have any link for documentation about multi threading in `C#` – X Dev Nov 02 '20 at 12:34
  • there are a lot of tutorials and examples out there, quick google will find tons. Can recommend this book if you want a truly deep understanding - https://www.apress.com/gb/book/9781430259206?gclid=EAIaIQobChMIyZit7vPj7AIViZntCh1qqAHiEAQYBSABEgIAKvD_BwE – NDJ Nov 02 '20 at 12:55