如何在页面加载中使用parallel?

时间:2016-07-15 12:12:23

标签: c# parallel-processing

我没有这样的连接:

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;
}

在page_load中按顺序工作。我需要并行运行这个连接。我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

使用 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;
}

答案 1 :(得分:0)

异步启动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());

答案 2 :(得分:0)

使用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;
        }
    }