Task.run not working for Database connections
up vote
0
down vote
favorite
When I am using Task.run(), the console application is automatically stopping while creating a new SqlConnection(),
If I use normally Its working fine. I am unable to create a new connection in the console application.
namespace ConsoleApplication1
{
class Program
{
static void Main(string args)
{
new Program().startTAsk();
}
public async void startTAsk()
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < 1; i++)
{
tasks.Add(Task.Run(() => this.connectDB()));
}
await Task.WhenAll(tasks);
}
public void connectDB()
{
string dbDynamicConnectionString = "Data Source=192.168.1.20;Initial Catalog=Test;Persist Security Info=True;User ID=Test;Password=Test";
bool ret = false;
SqlConnection connection = null;
try
{
using (connection = new SqlConnection(dbDynamicConnectionString))
{
//connect to db
}
}
catch (Exception ex)
{
console.writeLine("exception");
}
}
}
}
c# ado.net task task-parallel-library console-application
|
show 14 more comments
up vote
0
down vote
favorite
When I am using Task.run(), the console application is automatically stopping while creating a new SqlConnection(),
If I use normally Its working fine. I am unable to create a new connection in the console application.
namespace ConsoleApplication1
{
class Program
{
static void Main(string args)
{
new Program().startTAsk();
}
public async void startTAsk()
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < 1; i++)
{
tasks.Add(Task.Run(() => this.connectDB()));
}
await Task.WhenAll(tasks);
}
public void connectDB()
{
string dbDynamicConnectionString = "Data Source=192.168.1.20;Initial Catalog=Test;Persist Security Info=True;User ID=Test;Password=Test";
bool ret = false;
SqlConnection connection = null;
try
{
using (connection = new SqlConnection(dbDynamicConnectionString))
{
//connect to db
}
}
catch (Exception ex)
{
console.writeLine("exception");
}
}
}
}
c# ado.net task task-parallel-library console-application
2
Task.Runworks. Your code though doesn't wait for the task to complete (or even start) before exiting. It's the wrong way to execute SQL commands asynchronously too
– Panagiotis Kanavos
Nov 20 at 12:50
It's not throwing any exception. The console application exits. Even if I use await also its not working
– Hemanth Krishna
Nov 20 at 12:50
ADO.NET has asynchronous methods likeSqlConnection.OpenAsync()andSqlCommand.ExecuteReaderAsync(). You can have anasync Task Main()in C# 7+.
– Panagiotis Kanavos
Nov 20 at 12:51
I want to know why the code in above scenario is not working, Its not throwing any exceptions in debug mode.
– Hemanth Krishna
Nov 20 at 12:52
Even if I use awaithow? What does the code look like? Where did you use await? On the task itself or inside it? The code doesn't work because it doesn't await for that task to finish and exits immediatellly after the call to Task.Run
– Panagiotis Kanavos
Nov 20 at 12:52
|
show 14 more comments
up vote
0
down vote
favorite
up vote
0
down vote
favorite
When I am using Task.run(), the console application is automatically stopping while creating a new SqlConnection(),
If I use normally Its working fine. I am unable to create a new connection in the console application.
namespace ConsoleApplication1
{
class Program
{
static void Main(string args)
{
new Program().startTAsk();
}
public async void startTAsk()
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < 1; i++)
{
tasks.Add(Task.Run(() => this.connectDB()));
}
await Task.WhenAll(tasks);
}
public void connectDB()
{
string dbDynamicConnectionString = "Data Source=192.168.1.20;Initial Catalog=Test;Persist Security Info=True;User ID=Test;Password=Test";
bool ret = false;
SqlConnection connection = null;
try
{
using (connection = new SqlConnection(dbDynamicConnectionString))
{
//connect to db
}
}
catch (Exception ex)
{
console.writeLine("exception");
}
}
}
}
c# ado.net task task-parallel-library console-application
When I am using Task.run(), the console application is automatically stopping while creating a new SqlConnection(),
If I use normally Its working fine. I am unable to create a new connection in the console application.
namespace ConsoleApplication1
{
class Program
{
static void Main(string args)
{
new Program().startTAsk();
}
public async void startTAsk()
{
List<Task> tasks = new List<Task>();
for (int i = 0; i < 1; i++)
{
tasks.Add(Task.Run(() => this.connectDB()));
}
await Task.WhenAll(tasks);
}
public void connectDB()
{
string dbDynamicConnectionString = "Data Source=192.168.1.20;Initial Catalog=Test;Persist Security Info=True;User ID=Test;Password=Test";
bool ret = false;
SqlConnection connection = null;
try
{
using (connection = new SqlConnection(dbDynamicConnectionString))
{
//connect to db
}
}
catch (Exception ex)
{
console.writeLine("exception");
}
}
}
}
c# ado.net task task-parallel-library console-application
c# ado.net task task-parallel-library console-application
edited Nov 20 at 13:03
asked Nov 20 at 12:48
Hemanth Krishna
378
378
2
Task.Runworks. Your code though doesn't wait for the task to complete (or even start) before exiting. It's the wrong way to execute SQL commands asynchronously too
– Panagiotis Kanavos
Nov 20 at 12:50
It's not throwing any exception. The console application exits. Even if I use await also its not working
– Hemanth Krishna
Nov 20 at 12:50
ADO.NET has asynchronous methods likeSqlConnection.OpenAsync()andSqlCommand.ExecuteReaderAsync(). You can have anasync Task Main()in C# 7+.
– Panagiotis Kanavos
Nov 20 at 12:51
I want to know why the code in above scenario is not working, Its not throwing any exceptions in debug mode.
– Hemanth Krishna
Nov 20 at 12:52
Even if I use awaithow? What does the code look like? Where did you use await? On the task itself or inside it? The code doesn't work because it doesn't await for that task to finish and exits immediatellly after the call to Task.Run
– Panagiotis Kanavos
Nov 20 at 12:52
|
show 14 more comments
2
Task.Runworks. Your code though doesn't wait for the task to complete (or even start) before exiting. It's the wrong way to execute SQL commands asynchronously too
– Panagiotis Kanavos
Nov 20 at 12:50
It's not throwing any exception. The console application exits. Even if I use await also its not working
– Hemanth Krishna
Nov 20 at 12:50
ADO.NET has asynchronous methods likeSqlConnection.OpenAsync()andSqlCommand.ExecuteReaderAsync(). You can have anasync Task Main()in C# 7+.
– Panagiotis Kanavos
Nov 20 at 12:51
I want to know why the code in above scenario is not working, Its not throwing any exceptions in debug mode.
– Hemanth Krishna
Nov 20 at 12:52
Even if I use awaithow? What does the code look like? Where did you use await? On the task itself or inside it? The code doesn't work because it doesn't await for that task to finish and exits immediatellly after the call to Task.Run
– Panagiotis Kanavos
Nov 20 at 12:52
2
2
Task.Run works. Your code though doesn't wait for the task to complete (or even start) before exiting. It's the wrong way to execute SQL commands asynchronously too– Panagiotis Kanavos
Nov 20 at 12:50
Task.Run works. Your code though doesn't wait for the task to complete (or even start) before exiting. It's the wrong way to execute SQL commands asynchronously too– Panagiotis Kanavos
Nov 20 at 12:50
It's not throwing any exception. The console application exits. Even if I use await also its not working
– Hemanth Krishna
Nov 20 at 12:50
It's not throwing any exception. The console application exits. Even if I use await also its not working
– Hemanth Krishna
Nov 20 at 12:50
ADO.NET has asynchronous methods like
SqlConnection.OpenAsync() and SqlCommand.ExecuteReaderAsync(). You can have an async Task Main() in C# 7+.– Panagiotis Kanavos
Nov 20 at 12:51
ADO.NET has asynchronous methods like
SqlConnection.OpenAsync() and SqlCommand.ExecuteReaderAsync(). You can have an async Task Main() in C# 7+.– Panagiotis Kanavos
Nov 20 at 12:51
I want to know why the code in above scenario is not working, Its not throwing any exceptions in debug mode.
– Hemanth Krishna
Nov 20 at 12:52
I want to know why the code in above scenario is not working, Its not throwing any exceptions in debug mode.
– Hemanth Krishna
Nov 20 at 12:52
Even if I use await how? What does the code look like? Where did you use await? On the task itself or inside it? The code doesn't work because it doesn't await for that task to finish and exits immediatellly after the call to Task.Run– Panagiotis Kanavos
Nov 20 at 12:52
Even if I use await how? What does the code look like? Where did you use await? On the task itself or inside it? The code doesn't work because it doesn't await for that task to finish and exits immediatellly after the call to Task.Run– Panagiotis Kanavos
Nov 20 at 12:52
|
show 14 more comments
1 Answer
1
active
oldest
votes
up vote
1
down vote
This code has an obvious problem - it never waits for the task to complete and exits before it even starts.
There's nothing wrong with Task.Run to begin with, but it does start another thread. SqlClient offers true asynchronous methods though which don't take up a thread just to block it while waiting.
The code could be rewritten this way:
static async Task RunSomeCommand(string connString)
{
try
{
using (var connection = new SqlConnection(connString))
{
var cmd=new SqlCommand(...);
await connection.OpenAsync();
await cmd.ExecuteNonQueryAsync();
}
}
catch (Exception ex)
{
console.writeLine("exception");
}
}
static async Task RunManyCommands()
{
var listOfConnections=new List<string>();
//Somehow load all connection strings
var tasks = from cn in listOfConnections
select RunSomeCommand(cn);
await Task.WhenAll(tasks);
}
class Program
{
static async Task Main(string args)
{
Console.WriteLine("Starting");
await RunManyCommands();
Console.WriteLine("Finished");
}
}
RunSomeCommand opens a connection and executes a command asynchronously. RunManyCommands starts multiple asynchronous operations and awaits all of them to complete. Finally Main itself awaits RunManyCommands to finish before terminating
Task.waitAll() also working instead of await Task.WhenAll() and making the main () method async
– Hemanth Krishna
Nov 20 at 13:14
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53393350%2ftask-run-not-working-for-database-connections%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
1
down vote
This code has an obvious problem - it never waits for the task to complete and exits before it even starts.
There's nothing wrong with Task.Run to begin with, but it does start another thread. SqlClient offers true asynchronous methods though which don't take up a thread just to block it while waiting.
The code could be rewritten this way:
static async Task RunSomeCommand(string connString)
{
try
{
using (var connection = new SqlConnection(connString))
{
var cmd=new SqlCommand(...);
await connection.OpenAsync();
await cmd.ExecuteNonQueryAsync();
}
}
catch (Exception ex)
{
console.writeLine("exception");
}
}
static async Task RunManyCommands()
{
var listOfConnections=new List<string>();
//Somehow load all connection strings
var tasks = from cn in listOfConnections
select RunSomeCommand(cn);
await Task.WhenAll(tasks);
}
class Program
{
static async Task Main(string args)
{
Console.WriteLine("Starting");
await RunManyCommands();
Console.WriteLine("Finished");
}
}
RunSomeCommand opens a connection and executes a command asynchronously. RunManyCommands starts multiple asynchronous operations and awaits all of them to complete. Finally Main itself awaits RunManyCommands to finish before terminating
Task.waitAll() also working instead of await Task.WhenAll() and making the main () method async
– Hemanth Krishna
Nov 20 at 13:14
add a comment |
up vote
1
down vote
This code has an obvious problem - it never waits for the task to complete and exits before it even starts.
There's nothing wrong with Task.Run to begin with, but it does start another thread. SqlClient offers true asynchronous methods though which don't take up a thread just to block it while waiting.
The code could be rewritten this way:
static async Task RunSomeCommand(string connString)
{
try
{
using (var connection = new SqlConnection(connString))
{
var cmd=new SqlCommand(...);
await connection.OpenAsync();
await cmd.ExecuteNonQueryAsync();
}
}
catch (Exception ex)
{
console.writeLine("exception");
}
}
static async Task RunManyCommands()
{
var listOfConnections=new List<string>();
//Somehow load all connection strings
var tasks = from cn in listOfConnections
select RunSomeCommand(cn);
await Task.WhenAll(tasks);
}
class Program
{
static async Task Main(string args)
{
Console.WriteLine("Starting");
await RunManyCommands();
Console.WriteLine("Finished");
}
}
RunSomeCommand opens a connection and executes a command asynchronously. RunManyCommands starts multiple asynchronous operations and awaits all of them to complete. Finally Main itself awaits RunManyCommands to finish before terminating
Task.waitAll() also working instead of await Task.WhenAll() and making the main () method async
– Hemanth Krishna
Nov 20 at 13:14
add a comment |
up vote
1
down vote
up vote
1
down vote
This code has an obvious problem - it never waits for the task to complete and exits before it even starts.
There's nothing wrong with Task.Run to begin with, but it does start another thread. SqlClient offers true asynchronous methods though which don't take up a thread just to block it while waiting.
The code could be rewritten this way:
static async Task RunSomeCommand(string connString)
{
try
{
using (var connection = new SqlConnection(connString))
{
var cmd=new SqlCommand(...);
await connection.OpenAsync();
await cmd.ExecuteNonQueryAsync();
}
}
catch (Exception ex)
{
console.writeLine("exception");
}
}
static async Task RunManyCommands()
{
var listOfConnections=new List<string>();
//Somehow load all connection strings
var tasks = from cn in listOfConnections
select RunSomeCommand(cn);
await Task.WhenAll(tasks);
}
class Program
{
static async Task Main(string args)
{
Console.WriteLine("Starting");
await RunManyCommands();
Console.WriteLine("Finished");
}
}
RunSomeCommand opens a connection and executes a command asynchronously. RunManyCommands starts multiple asynchronous operations and awaits all of them to complete. Finally Main itself awaits RunManyCommands to finish before terminating
This code has an obvious problem - it never waits for the task to complete and exits before it even starts.
There's nothing wrong with Task.Run to begin with, but it does start another thread. SqlClient offers true asynchronous methods though which don't take up a thread just to block it while waiting.
The code could be rewritten this way:
static async Task RunSomeCommand(string connString)
{
try
{
using (var connection = new SqlConnection(connString))
{
var cmd=new SqlCommand(...);
await connection.OpenAsync();
await cmd.ExecuteNonQueryAsync();
}
}
catch (Exception ex)
{
console.writeLine("exception");
}
}
static async Task RunManyCommands()
{
var listOfConnections=new List<string>();
//Somehow load all connection strings
var tasks = from cn in listOfConnections
select RunSomeCommand(cn);
await Task.WhenAll(tasks);
}
class Program
{
static async Task Main(string args)
{
Console.WriteLine("Starting");
await RunManyCommands();
Console.WriteLine("Finished");
}
}
RunSomeCommand opens a connection and executes a command asynchronously. RunManyCommands starts multiple asynchronous operations and awaits all of them to complete. Finally Main itself awaits RunManyCommands to finish before terminating
answered Nov 20 at 13:12
Panagiotis Kanavos
53.1k479107
53.1k479107
Task.waitAll() also working instead of await Task.WhenAll() and making the main () method async
– Hemanth Krishna
Nov 20 at 13:14
add a comment |
Task.waitAll() also working instead of await Task.WhenAll() and making the main () method async
– Hemanth Krishna
Nov 20 at 13:14
Task.waitAll() also working instead of await Task.WhenAll() and making the main () method async
– Hemanth Krishna
Nov 20 at 13:14
Task.waitAll() also working instead of await Task.WhenAll() and making the main () method async
– Hemanth Krishna
Nov 20 at 13:14
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53393350%2ftask-run-not-working-for-database-connections%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
Task.Runworks. Your code though doesn't wait for the task to complete (or even start) before exiting. It's the wrong way to execute SQL commands asynchronously too– Panagiotis Kanavos
Nov 20 at 12:50
It's not throwing any exception. The console application exits. Even if I use await also its not working
– Hemanth Krishna
Nov 20 at 12:50
ADO.NET has asynchronous methods like
SqlConnection.OpenAsync()andSqlCommand.ExecuteReaderAsync(). You can have anasync Task Main()in C# 7+.– Panagiotis Kanavos
Nov 20 at 12:51
I want to know why the code in above scenario is not working, Its not throwing any exceptions in debug mode.
– Hemanth Krishna
Nov 20 at 12:52
Even if I use awaithow? What does the code look like? Where did you use await? On the task itself or inside it? The code doesn't work because it doesn't await for that task to finish and exits immediatellly after the call to Task.Run– Panagiotis Kanavos
Nov 20 at 12:52