Async In Targeting .NET 4.0方法

时间:2016-03-14 01:42:06

标签: c# asp.net webforms task

我在webform .net 4.0项目中使用以下语法。但是,一旦它到达dropdown1.DataSource = tasks[0].Result.Tables[0];我就会收到NullReferenceException错误。

我知道通常会抛出此错误,因为没有进行正确的分配,但是,在我的语法中,我认为我需要完成所有适用的分配。我需要在下面的语法中更改/更改/修改以便正确填充下拉列表?

namespace NETAsyncLowVersion
{
public partial class WebformLVAsync : System.Web.UI.UserControl
{
    private class1 _class1 = new NC1();
    private DataSet DS = new DataSet();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Task.Factory.ContinueWhenAll(new[]{ SqlQuery1() }, tasks =>
            {
                try 
                {
                    dropdown1.DataSource = tasks[0].Result.Tables[0];
                }
                catch (Exception exception) { throw exception; }
            }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
        }
    }
    private void SqlQuery1()
    {
        dropdown1.DataSource = _class1.SqlQuery1(databaseconn);
    }

public class class1
{
    private DataSet DS = new DataSet();
    private Databaselayer _Databaselayer = new Databaselayer();

    public DataSet SqlQuery1(string databaseConnection)
    {
        DS = new DataSet();
        _Databaselayer.SqlQueryBuilder = new StringBuilder();
        _Databaselayer.SqlQueryBuilder.Append("Select managername from salesdatabase");
        return _Databaselayer.FDS(databaseConnection, _Databaselayer.SqlQueryBuilder.ToString());
    }           
}
public class Databaselayer
{
    public System.Threading.Tasks.Task<DataSet> FDS(string connectionString, string sqlQuery)
    {
        return System.Threading.Tasks.Task.Factory.StartNew(() =>
        {
            var dataSet = new DataSet();
            using (var adapter = new SqlDataAdapter(sqlQuery, connectionString))
                adapter.Fill(dataSet);

            return dataSet;
        });
    }
}
}    

1 个答案:

答案 0 :(得分:0)

我在另一个问题中谈过这个问题:Use 1 DataReader For Multiple Database Calls。在您的情况下,您处于用户控件中,然后您需要调用 Page.RegisterAsyncTask 方法而不是简单地 RegisterAsyncTask