[英]How can I use parallel for in page load?
I have few connections like this: 我很少有这样的联系:
try
{
OleDbConnection con1;
using (con1 = new OleDbConnection("Provider=MSDAORA.1;Data Source=db1:1521;Persist Security Info=True;Password=password;User ID=username"))
{
con1.Open();
v1 = 1;
con1.Close();
}
}
catch (Exception ex)
{
v1 = 0;
}
try
{
OleDbConnection con2;
using (con2 = new OleDbConnection("Provider=MSDAORA.1;Data Source=db2:1521;Persist Security Info=True;Password=password;User ID=username"))
{
con2.Open();
v2 = 1;
con2.Close();
}
}
catch (Exception ex)
{
v2 = 0;
}
In page_load and working in order. 在page_load中并按顺序工作。 I need parallel run this connections.
我需要并行运行此连接。 How can I do that?
我怎样才能做到这一点?
With C# 6 and .NET 4.5 you can use the TPL with async and the code looks even cleaner: 使用C#6和.NET 4.5,您可以将TPL与async一起使用,并且代码看起来更加简洁:
static void Main()
{
var v1Task = Connect();
var v2Task = Connect();
var results = Task.WhenAll(v1Task, v2Task);
var v1 = results.Result[0];
var v2 = results.Result[1];
}
static async Task<int> Connect()
{
int v;
try
{
using (var con2 = new OleDbConnection("Provider=MSDAORA.1;Data Source=db2:1521;Persist Security Info=True;Password=password;User ID=username"))
{
await con2.OpenAsync();
v = 1;
con2.Close();
}
}
catch (Exception)
{
v = 0;
}
return v;
}
Start con1 and con2 asynchronously and wait until both tasks are finished 异步启动con1和con2,然后等待两个任务完成
var task1 = Task.Run(() =>
{
try
{
using (OleDbConnection con1 = new OleDbConnection("Provider=MSDAORA.1;Data Source=db1:1521;Persist Security Info=True;Password=password;User ID=username"))
{
con1.Open();
v1 = 1;
con1.Close();
}
}
catch (Exception ex)
{
v1 = 0;
}
});
var task2 = Task.Run(() =>
{
try
{
using (OleDbConnection con2 = new OleDbConnection("Provider=MSDAORA.1;Data Source=db2:1521;Persist Security Info=True;Password=password;User ID=username"))
{
con2.Open();
v2 = 1;
con2.Close();
}
}
catch (Exception ex)
{
v2 = 0;
}
});
// If you need to wait until task1 and task2 finished, then use this:
List<Task> tasks = new List<Task>();
tasks.Add(task1);
tasks.Add(task2);
Task.WaitAll(tasks.ToArray());
Using parallel.for: 使用parallel.for:
static void Main(string[] args)
{
ConcurrentDictionary<string, int> results = new ConcurrentDictionary<string, int>();
string[] connStrings = new string[]{"connstring1", "connstring2"};
Parallel.For(0, connStrings.Length, (i) => {
results[connStrings[i]] = TryToConnectToDatabase(connStrings[i]);
});
}
static int TryToConnectToDatabase(string connstr)
{
try
{
OleDbConnection con1;
using (con1 = new OleDbConnection(connstr))
{
con1.Open();
con1.Close();
return 1;
}
}
catch (Exception ex)
{
return 0;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.