[英]Thread Safe Grid View Update in C# .Net
我正在詳細解釋我的問題。 我在Windows主窗體中有一個dataGridView
。 我有一個計時器,當單擊button1時該計時器開始計時。 當單擊button2時,它停止。
現在,與此同時,我正在計算某些內容並將其放入dataGridView
。 這是一個動態計算。 在此計算中,我使用了線程。 (我絕對不是Threads的新手)。 我已經使用Thread.Sleep(100)
來計算數據。 現在,我在循環中使用Thread.Sleep來計算連續事物的數據。 我希望保留計算的各個順序。 循環的每次迭代后,我都使用dataGridView.Rows.AddRange(DataGridViewRow)
添加帶有計算出的新數據的新行。
但是我沒有按順序在dataGridView中獲取數據,並且也無法正常運行。 它在某個時間變得空白,並且隨機出現。
PS-每次計時器間隔結束時,我都會清除數據。
在嘗試更新datagridview之前,您需要調用datagridview.InvokeRequired。 如果是這樣,則調用Invoke傳遞您要執行的委托以及要傳遞的任何數據。
已解決。 實際上,您必須設置Thread.Sleep
計時器,以使其在Windows.Forms.Timer
的間隔結束之前完成。
這是設置Gridview的線程安全方法。
class Program
{
public static List<string> ChoiceExtension = new List<string>();
static void Main()
{
ChoiceExtension.Add("One");
ChoiceExtension.Add("Two");
ChoiceExtension.Add("Three");
//Set list as gridsource
InserttoGrid(ChoiceExtension);
}
public static void SetDataSource(object value)
{
DataTable dt = new DataTable();
dt.Columns.Add("Path of Extension");
foreach (var item in value as List<string>)
{
dt.Rows.Add(new object[] { item });
}
ExtensionList.DataSource = dt;
}
public static void InserttoGrid(List<string> List)
{
if (ChoiceExtension.Count >0)
{
if (this.ExtensionList.InvokeRequired)
{
ExtensionList.Invoke(new SetDataSourceDelegate(SetDataSource), new Object[] { List });
}
else
{
SetDataSource(List);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.