5

I have a try-catch for oledbconnection like this:

try
{
        OleDbConnection Connection;
        using (Connection = new OleDbConnection("Provider=MSDAORA.1;Data Source=DATABASE:1521/orcl//orcl1;Persist Security Info=True;Password=PASS;User ID=USER"))
        {
            Connection.Open();
            v1 = 1;
            Connection.Close();
        }
}
catch (Exception)
{
        v1 = 0;
}

When I can't connect database, try going to catch and return v1 = 0. It's working but when connection waiting so much(for example 30-40 seconds), try trying to connect and page waiting so much.

I tried Connect Timeout for oledbconnection but does not working.

I need to use try for few secs, if any problem, need to go catch.

How can I do that?

onur
  • 5,647
  • 3
  • 23
  • 46

2 Answers2

7

Assuming you are using .net 4.5 then you can benefit the Task timeout and async await capabilities:

int timeout = 1000;
var task = SomeOperationAsync();
if (await Task.WhenAny(task, Task.Delay(timeout)) == task) {
    // task completed within timeout
} else { 
    // timeout logic
}

More info here

In case you are stuck with .net 3.5 or older:

using System.Threading;

class Program {
    static void DoSomething() {
        try {
            // your call here...
            obj.PerformInitTransaction();         
        } catch (ThreadAbortException) {
            // cleanup code, if needed...
        }
    }

    public static void Main(params string[] args) {

        Thread t = new Thread(DoSomething);
        t.Start();
        if (!t.Join(TimeSpan.FromSeconds(30))) {
            t.Abort();
            throw new Exception("More than 30 secs.");
        }
    }
}

More info here

Community
  • 1
  • 1
vezenkov
  • 4,009
  • 1
  • 26
  • 27
  • 1
    Note that this is a general answer for any operation that you need to timeout. The OLE DB connections should support a timeout (specified in connection string) that works! – vezenkov Jul 29 '15 at 06:54
0

I don't see 'Connect Timeout={seconds};" in your connection string. As mentioned here

the ConnectionTimeout property is read-only. You have to set the timeout in the connection string instead by using Connect Timeout=30;

and don't forget ';'

Community
  • 1
  • 1
AntonS
  • 341
  • 1
  • 8