How can I use timeout for try-catch?

onur picture onur · Jul 29, 2015 · Viewed 11.7k times · Source

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?

Answer

vezenkov picture vezenkov · Jul 29, 2015

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