gpt4 book ai didi

c# - 在 C# 中为多线程锁定 DataTable 的正确方法?

转载 作者:太空狗 更新时间:2023-10-29 23:00:41 24 4
gpt4 key购买 nike

这是锁定和修改由多个线程共享的 DataTable 的正确方法吗?如果不是,那么正确的方法是什么?

private void DoGeocodeLookup(object info)
{
ParameterRow data = (ParameterRow)info;
DataRow dr = data.Dr;
int localIndex = data.Index;
ManualResetEvent doneEvent = data.m_doneEvent;

Geocode_Google.GeoCode gc = new GeoCode();

gc.Addr_In = m_dtAddress.Rows[localIndex]["AddressStd_tx"].ToString();

gc.GeoCodeOne();

if (gc.Status == "OK")
{
//write back to temporary datatable
lock( m_TempTable.Rows.SyncRoot )
{
m_TempTable.Rows[localIndex]["GL_Address"] = gc.Thoroughfare_tx;
}
}
doneEvent.Set();
}

我的结构:

struct ParameterRow
{
private DataRow m_row;
private int m_index;

public DataRow Dr
{
get { return m_row; }
set { m_row = value; }
}

public int Index
{
get { return m_index; }
set { m_index = value; }
}

public ManualResetEvent m_doneEvent;

public ParameterRow( DataRow row, int index, ManualResetEvent doneEvent)
{
m_row = row;
m_index = index;
m_doneEvent = doneEvent;
}
}

我开始所有线程的片段:

//make temporary table
m_TempTable = new DataTable();
m_TempTable = m_dtAddress.Copy();

for (int index = 0; index < m_geocodes; index++)
{
doneEvents[index] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(DoGeocodeLookup, new ParameterRow( m_dtAddress.Rows[index], index, doneEvents[index]));
}

WaitHandle.WaitAll(doneEvents);

最佳答案

您的示例不需要对 DataTable 进行任何锁定。在 DoGeocodeLookup 中,您只执行对 DataTable 的读取。您对表执行的唯一访问是查找一行,这算作一次读取。 DataTable类被标记为对多线程读取操作是安全的。如果您在 DoGeocodeLookup 中执行添加新行之类的操作,那么您将需要锁定。

您唯一要更改的是 localIndex 指定的单个 DataRow 中的数据。由于对 DoGeocodeLookup 的每次调用都使用不同的行 - 表中的一行只会由一个线程更新,因此您在那里没有同步问题。所以这也不需要锁定。

关于c# - 在 C# 中为多线程锁定 DataTable 的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14201939/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com