DataGridViewの列にサムネイル画像を挿入する必要があります。 DataGridViewImageCell.Value を非同期的ににロードしたいのですが、画像のダウンロードに時間がかかるためです。DataGridViewImageCell非同期画像のロード
このソリューションは、画像を非同期に読み込みますが、UIスレッドが他のタスクを実行するのを妨げています(アプリケーションのメッセージキューが.BeginInvoke呼び出しで満たされているためです)。
イメージのダウンロード中にユーザーがグリッドをスクロールできるようにするには、どうすればできますか?あなたのイベントハンドラ非同期にすることにより
private void LoadButton_Click(object sender, EventArgs e)
{
myDataGrid.Rows.Clear();
// populate with sample data...
for (int index = 0; index < 200; ++index)
{
var itemId = r.Next(1, 1000);
var row = new DataGridViewRow();
// itemId column
row.Cells.Add(new DataGridViewTextBoxCell
{
ValueType = typeof(int),
Value = itemId
});
// pix column
row.Cells.Add(new DataGridViewImageCell
{
ValueType = typeof(Image),
ValueIsIcon = false
});
// pre-size height for 90x120 Thumbnails
row.Height = 121;
myDataGrid.Rows.Add(row);
// Must be a "better" way to do this...
GetThumbnailForRow(index, itemId).ContinueWith((i) => SetImage(i.Result));
}
}
private async Task<ImageResult> GetThumbnailForRow(int rowIndex, int itemId)
{
// in the 'real world' I would expect 20% cache hits.
// the rest of the images are unique and will need to be downloaded
// emulate cache retrieval and/or file download
await Task.Delay(500 + r.Next(0, 1500));
// return an ImageResult with rowIndex and image
return new ImageResult
{
RowIndex = rowIndex,
Image = Image.FromFile("SampleImage.jpg")
};
}
private void SetImage(ImageResult imageResult)
{
// this is always true when called by the ContinueWith's action
if (myDataGrid.InvokeRequired)
{
myDataGrid.BeginInvoke(new Action<ImageResult>(SetImage), imageResult);
return;
}
myDataGrid.Rows[imageResult.RowIndex].Cells[1].Value = imageResult.Image;
}
private class ImageResult
{
public int RowIndex { get; set; }
public Image Image { get; set; }
}
1つのイメージに対してタスクをスローできます。このタスクが終了したら、次のイメージをロードして最後のイメージまで繰り返します。 – McNets
答えがないのだろうか?どんな解決策でもUIスレッドにメッセージを送信し、ユーザーメッセージを処理する能力が低下するように見えるでしょう。私は私の "エミュレート"遅延を増やすことでそれをテストすることができます。 – Tony
テスト結果 - 私はエミュレートされた遅延を5000-7500 mSに増やしました.5秒間グリッドをナビゲートすることができました。その後、画像が入力されるとロックされました。うーん。 – Tony