本文介绍了填充数据集异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下方法正用于填充数据集.

Below method is getting used to fill Dataset.

如果我们以同步方式调用此方法,则它工作正常.

if we are calling this method in synchronous way it is working fine.

但是现在我们需要以异步方式调用此方法.因此,我需要做些什么更改,以便下面的方法可以正常工作而没有任何问题.

But now we need to call this method in Asynchronous way.so what changes i need to do so that below method should work properly without any issue.

public DataSet Filldata(string ProcName, string TableName)
{
    DataSet ds = new DataSet();
    try
    {
        da = new SqlDataAdapter(ProcName, con);
        if (con.State != ConnectionState.Open)
        {
            con.Open();
        }
        da.SelectCommand.CommandTimeout = 15000;
        da.Fill(ds, TableName);
    }
    catch (Exception ex)
    {
        ErrorMsg = ex.Message.ToString();
        HMISLogger.logger.Error(ex.Message.ToString() + " " + ProcName, ex);
    }
    finally
    {
        con.Close();
        da.Dispose();
    }
    return ds;
}

推荐答案

您可以如下声明类级静态对象

You can declare the class level static object as below

private static object lockObject = new object();

并如下修改您的方法,因为Fill方法负责连接的打开和关闭,所以我们可以在它之前添加lock语句.

And modify the your method as below , As Fill method takes care of connection open and close we can add lock statement before it.

 public DataSet Filldata(string ProcName, string TableName)
        {
            DataSet ds = new DataSet();
            try
            {

                da = new SqlDataAdapter(ProcName, con);
                da.SelectCommand.CommandTimeout = 15000;
                lock (lockObj)
                {
                    da.Fill(ds, TableName);
                }
            }
            catch (Exception ex) {
                ErrorMsg = ex.Message.ToString();
                HMISLogger.logger.Error(ex.Message.ToString() + " " + ProcName, ex);
            }
            finally {
                con.Close();
                da.Dispose();
            }
            return ds;
        }

这篇关于填充数据集异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 21:28