簡體   English   中英

Parallel.ForEach和DataGridViewRow

[英]Parallel.ForEach and DataGridViewRow

我在轉換時遇到問題。 Parallel.ForEach AsParallel 我有一個DataGridView ,我用ForEach循環將一些值放在它的第一列中,然后將值發送給方法並獲得返回值,然后將返回值放入第二列。

一開始 我使用的是ForEach循環,但是花費了太多時間,於是我決定使用。 AsParallel但我認為,就我而言,最好使用Parallel.ForEach但我無法使其與datagridviewrow

ForEach方法:

 foreach (DataGridViewRow dgvRow in dataGrid1.Rows)
 {
     // SOME CODES REMOVED FOR CLARITY
     string data1 = row.Cells[1].Value;
     var returnData = getHtml(data1);
     row.Cells[2].Value = returnData;
 }

AsParallel方法:

dataGrid1.Rows.Cast<DataGridViewRow>().AsParallel().ForAll(row =>
{
    // SOME CODES REMOVED FOR CLARITY
    string data1 = row.Cells[1].Value;
    var returnData = getHtml(data1);
    row.Cells[2].Value = returnData;
}); 

那么,如何將Parallel.ForEach循環與DataGridViewRow (DataGridView)配合使用?

謝謝。

如果getHtml (以及循環的其他非UI部分)相對昂貴,則可以並行執行您要嘗試的操作,如果價格便宜,則並行進行更新是沒有意義的。 UI(您的數據網格)無論如何都必須是順序的,因為只有UI線程可以更新它。

如果getHtml (以及循環的其他非UI部分)相對昂貴,則可以執行以下操作:

var current_synchronization_context = TaskScheduler.FromCurrentSynchronizationContext();

Task.Factory.StartNew(() => //This is important to make sure that the UI thread can return immediately and then be able to process UI update requests
{
    Parallel.ForEach(dataGrid1.Rows.Cast<DataGridViewRow>(), row =>
    {
        // SOME CODES REMOVED FOR 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 will request a UI update on the UI thread and return immediately
    }); 
});

創建Task並使用TaskScheduler.FromCurrentSynchronizationContext()將在Windows Forms應用程序和WPF應用程序中工作。

如果您不想為每個UI更新計划一個Task,則可以直接調用BeginInvoke方法(如果這是Windows Forms應用程序),如下所示:

dataGrid1.BeginInvoke((Action)(() =>
{
    row.Cells[2].Value = returnData;
}));

我上面的建議將導致數據在處理/生成時呈現到UI。

如果您不關心此問題,並且可以先處理所有數據然后更新UI,則可以執行以下操作:

1)從UI線程中的UI收集所有數據

2)通過Parallel.ForEach處理數據並將結果存儲在數組中

3)將數據從UI線程渲染到UI

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM