VB.NET - 从一个线程类实例中访问数据集?

时间:2011-11-01 21:04:34

标签: vb.net multithreading visual-studio-2010 dataset

我在一个类中使用以下代码,并在我的主窗体(Main.vb)中创建该类的实例:

Dim count As Integer = Main.DbDataSet.Accounts.Count

这会返回我的数据库中的帐户数。

更改代码后,我可以在后台线程中运行它以保存锁定程序,因为在此点之后处理更多数据,计数每次都返回0。

是否可以在线程进程(另一个类)中访问我的DbDataSet?

1 个答案:

答案 0 :(得分:0)

根据您的描述,我认为您必须阅读有关线程的更多信息。这是为了确保您知道您正在玩双刃刀片(线程)。你可以在网上找到很少的好材料。即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; }
}