【问题标题】:VB.NET - Accessing A Dataset From Within A Threaded Class Instance?VB.NET - 从线程类实例中访问数据集?
【发布时间】:2011-12-19 20:22:32
【问题描述】:
我在一个类中使用以下代码并从我的主窗体 (Main.vb) 中创建该类的一个实例:
Dim count As Integer = Main.DbDataSet.Accounts.Count
这是返回我的数据库中的帐户数。
在更改代码以便我可以在后台线程中运行它以节省锁定程序之后,随着在此之后处理更多数据,计数每次都返回 0。
是否可以在线程进程(另一个类)中访问我的 DbDataSet?
【问题讨论】:
标签:
vb.net
multithreading
visual-studio-2010
dataset
【解决方案1】:
根据您的描述,我认为您必须阅读有关线程的更多信息。这是为了确保您知道自己在玩双刃刀片(穿线)。您可以在网上找到很少的好材料。即C#中的threading。
现在,由于对您最终要做什么的了解有限;下面的代码绘制了代码应该是什么样子的蓝图。
class YourForm
{
private DataSet dataSet;
public int Count { get; set; }
SynchronizationContext runningContext;
public YourForm()
{
}
void FillData()
{
//fill your dataset with required data
}
void ProcessInWorker()
{
runningContext=SynchronizationContext.Current;
Two secondClass = new Two();
secondClass.DoWork +=secondClass_DoWork;
secondClass.RunWorkerCompleted +=secondClass_RunWorkerCompleted;
YourRequest re=new YourRequest()
{
DatasetToSend=dataSet
}
secondClass.RunWorkerAsync(re);
}
void secondClass_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null) throw e.Error;
YourResponse cResponse = e.Result as YourResponse;
if (cResponse == null) return;
dataSet = cResponse.RefilledData;//latest data will be here on completion of worker thread.
//if you want you can update latest count in some UI control say txtRecordCount
runningContext.Post(new SendOrPostCallback(delegate
{
txtRecordCount.Text=//give your row count here;
}), null);
}
void secondClass_DoWork(object sender, DoWorkEventArgs e)
{
try
{
YourRequest cRequest = e.Argument as YourRequest;
cRequest.DatasetToSend = RefillData();
YourResponse cResponse=new YourResponse()
{
RefilledData=cRequest.DatasetToSend
};
e.Result = cResponse;
}
catch
{
throw
}
}
DataSet RefillData()
{
//put your logic here to refill the data in dataset
//return the dataset;
}
}
class Two : BackgroundWorker
{
//sub classing background worker and rest of your own
//logic which you are planning for second class.
}
class YourRequest
{
public YourRequest ()
{
}
public DataSet DatasetToSend{get;set;}
}
class YourResponse
{
public YourResponse()
{
}
public DataSet RefilledData { get; set; }
}