C# Creating a generic task without starting it

686 views Asked by At

SHORT VERSION: I would like to create a GENERIC task that can be executed later, but I'm not sure of the syntax needed to do so.

LONG VERSION: I've built a custom Fluent syntax SQL Generator/ORM. It includes synchronous methods like...

var dt = DB.Select().From("TABLE_NAME").Where("WHERE CONDITIONS").ToDataTable(connString);
var dr = DB.Select().From("TABLE_NAME").Where("WHERE CONDITIONS").ToDataReader(connString);

that return a System.Data.DataTable/DataReader (old school, but I still have lots of legacy ADO.NET code to deal with).

I am now introducing async/await and Tasks to this generator. I want to create something like

var task1 = DB.Select().From("TABLE_NAME").Where("WHERE CONDITIONS").ToTask<DataTable>(connString);
var task2 = DB.Select().From("TABLE_NAME").Where("WHERE CONDITIONS").ToTask<DataRow>(connString);
var task3 = DB.Select().From("TABLE_NAME").Where("WHERE CONDITIONS").ToTask<DataReader>(connString);

Each task brings back a potentially different generic type. But I want delayed execution. I want to potentially bring back many tasks and then do a...

await Task.WhenAll(task1, task2, task3, etc...)

I am struggling on how to code that...here's my thoughts so far...

public Task<T> ToTask<T>(string connStr)
{
     Task<T> t = new Task<T>();  //maybe?

     //SetResult will block until loaded???
     TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
     tcs.SetResult((T) LoadThisGenericType(typeof(T)));
     return tcs.Task;
}

Am I biting off more than I can chew?? Any guidance would be appreciated.

UPDATE: Here is my implementation of ToDataReaderAsync for reference purposes...

public async Task<SqlDataReader> ToDataReaderAsync(string connStr)
{
    using (SqlConnection con = await DB.SQL.CreateConnectionAsync(connStr))
        using (SqlCommand cmd = DB.SQL.CreateCommand(con))
        {
            cmd.CommandText = "TEXT OF COMMAND HERE"; //Stored proc, INSERT, UPDATE, etc...
            return await cmd.ExecuteReaderAsync();
        }
}
0

There are 0 answers