I'm facing a little problem. I've made a function that imports customers from my website to my database to create invoices and so.. When this function starts, it calls another function to import only new clients. Now I want to make this last function an await to prevent that my software at home can search for the newly imported customers. This customer import is pretty easy, it just selects only the customers which are not imported through a loop. But I also made some security's in there in case something goes wrong. You know, most errors come from human input errors... But what is the best way to make this function an async so that the other function can await while it's importing new customers?
public async Task<bool> ImportClients(bool onlyNewCustomers)
{
System.Data.DataTable Table = new System.Data.DataTable();
System.Data.DataTable CustomerTable = new System.Data.DataTable();
System.Data.DataTable KlantTable = new System.Data.DataTable();
int PrestaCustomerID = 0; //original customer id from the prestashop
int CustomerID = 0; //Original customerID from software customer
int CustomerIdInserted = 0; //id from the inserted customer id in the software
int Wait = 0; //This var is used for the mysql to wait a few miliseconds between x updates
string Sql = "";
string Prefix = "";
DateTime Bday;
//Vars for logging
int CustomersImported = 0;
StringBuilder NewCustomerInfo = new StringBuilder();
StringBuilder NewCustomerAddress = new StringBuilder();
//Select everything whithin the customers table. After that we look if the customer is imported else we update the clients credentials.
Sql =
"SELECT c.id_customer, id_gender, c.firstname, c.lastname, c.email, c.birthday, c.newsletter, c.optin, c.website, " +
"c.active, c.date_add, c.date_upd, c.imported FROM ps_customer c " +
(onlyNewCustomers ? "WHERE imported = 0 " : "") + "ORDER BY c.id_customer DESC;";
Table = Functions.SelectWebQuery(Sql);
if (Table.Rows.Count > 0)
{
for (int i = 0; i < Table.Rows.Count; i++)
{
if (somethingGoesWrong)
{
return false;
}
}
return await Task.WhenAll<bool>(true);
}
}
And what i've tried to call this function
public async static void OrderImport()
{
Functions fns = new Functions();
bool importCustomers = await fns.ImportClients(true);
}
I'm using .net 4.5 with mysql database in winforms.
Thanks! Paul
async voidtoasync Task, you'll be able toawaitit then.SelectWebQueryfunction to become async. MySql connector has async interface mysqlconnector.net/tutorials/connect-to-mysql. But given you are running a single operation on one machine you won't see any improvements performance vise async make sense on high load setups. If you want to do it in the background so you don't block the UI thread use Task.Run it will work fine