c# - Parallel.ForEach and DataGridViewRow -


i'm having issue converting .asparallel parallel.foreach. have datagridview , i'm putting values in first column of after foreach loop i'm sending value method , getting return value i'm putting return value second column.

at beginning; using foreach loop takes time, decided use .asparallel think, in situation, might better use parallel.foreach couldn't make work datagridviewrow.

foreach method :

 foreach (datagridviewrow dgvrow in datagrid1.rows)  {      // codes removed clarity      string data1 = row.cells[1].value;      var returndata = gethtml(data1);      row.cells[2].value = returndata;  } 

asparallel method :

datagrid1.rows.cast<datagridviewrow>().asparallel().forall(row => {     // codes removed clarity     string data1 = row.cells[1].value;     var returndata = gethtml(data1);     row.cells[2].value = returndata; });  

so, how can use parallel.foreach loop datagridviewrow (datagridview) ?

thanks.

if gethtml (and other non-ui part of loop) relatively expensive, makes sense trying in parallel, if cheap not make sense in parallel because updating ui (your data grid) needs sequential anyway since ui thread can update it.

if gethtml (and other non-ui part of loop) relatively expensive, can following:

var current_synchronization_context = taskscheduler.fromcurrentsynchronizationcontext();  task.factory.startnew(() => //this important make sure ui thread can return , able process ui update requests {     parallel.foreach(datagrid1.rows.cast<datagridviewrow>(), row =>     {         // codes removed clarity         string data1 = row.cells[1].value;         var returndata = gethtml(data1); //expensive call          task.factory.startnew(() => row.cells[2].value = returndata,             cancellationtoken.none,             taskcreationoptions.none,             current_synchronization_context); //this request ui update on ui thread , return     });  }); 

creating task , using taskscheduler.fromcurrentsynchronizationcontext() work in windows forms application , in wpf application.

if don't want schedule task each ui update, can call begininvoke method directly (if windows forms application) this:

datagrid1.begininvoke((action)(() => {     row.cells[2].value = returndata; })); 

my suggestion above cause data rendered ui being processed/generated.

if don't care this, , ok processing data first , updating ui, can following:

1) collect data ui in ui thread

2) process data via parallel.foreach , store result in array

3) render data ui ui thread


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -