Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use timeout for try-catch?

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?

like image 511
onur Avatar asked Jul 29 '15 06:07

onur


People also ask

Can we use continue in try catch?

As you are saying that you are using try catch within a for each scope and you wants to continue your loop even any exception will occur. So if you are still using the try catch within the loop scope it will always run that even exception will occur. it is upto you how you deal with exception in your way.

What is a try catch?

The try-catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions. When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception.


1 Answers

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

like image 158
vezenkov Avatar answered Oct 02 '22 04:10

vezenkov