简体   繁体   中英

How to implement Multithreading in wpf

I want to implement multithreading in my wpf application.I have a list of tables and I need generate data files for each table concurrently.

Suppose I have a function called GenerateFiles,

  public void GenerateFiles()
    {
        //creating scripts
    }

and I have

  foreach(var table in tables)
      { 
     GenerateFiles();
      }

How can genrate the files using GenerateFiles() concurrently using threads? Is it correct ?

while(tables.count)
 {
      Thread th = new Thread();
      oThread.Start(new ThreadStart(GenerateFiles));
 }

How can I implement this using Multithreading ?

With your code you move the generation of the Files to a background thread. If you want to create them parallel you can use:

Parallel.ForEach(tables, table => 
{ 
  GenerateFiles();
}

If you want the files to be generated in the background and not affect the UI, you may want to wrap this inside a Task.

    Task.Run(()=>
    {
       Parallel.ForEach(tables, table => 
       { 
           GenerateFiles();
       }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM