How to run Asynchronous task and override it

Posted on Posted in C#

We need to run Asynchronous task due to some requirements but we want that to be override able, unfortunately that is not possible however we can create Asynchronous method but then call that method inside of Synchronous method and make it Virtual.

First we need to create an Asynchronous method which gets called in Synchronous method

public Task<string> CreateTestXmlAsync(QueueData q){
string sql = “SQL SCRIPT”;
if (string.IsNullOrEmpty(sql)) { return null; }
var data = Task.Run(async () =>
{
using (ServerContext context = new ServerContext(this.data))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql;
cmd.Parameters.Add(“@TestId”, SqlDbType.UniqueIdentifier).Value = q.TestId;
using (SqlDataReader reader = Database.ExecuteReader(cmd))
{
string xmlToReturn = string.Empty;
if (await reader.ReadAsync())
{
if (!reader.HasRows) { return null; }
xmlToReturn = reader[“testXml”].ToString();
}
return xmlToReturn;
}
}
}
});
return data;
}

Then need to create Synchronous method which returns a string

public virtual string CreateTestXmlSync(QueueData q)
{
var result = CreateTestXmlAsync(q).Result;
return result;
}

Now we can call Synchronous method anywhere we need to and override it if needed.

public override string CreateTestXmlSync(TelegramQueueItem q)
{
var xmlData = base.CreateTestXmlSync(q);
xmlData.Replace(“<testData>”, “”).Trim();
return xmlData;
}