Oracle Client vs. Task-based Asynchronous Pattern (async/await)

前端 未结 3 1316
闹比i
闹比i 2021-01-12 07:53

I\'d like to write a bunch of methods querying the Oracle Database in the async/await way. Since ODP.NET seems to support neither awaitable *Async methods nor Begin/EndOpera

3条回答
  •  旧时难觅i
    2021-01-12 08:21

    you can always use a Task.Factory.StartNew with the TaskCreationOptions.LongRunning, so that .NET will create a new thread rather than using a threadpool thread. Below is the manual asynchronous code that you can apply to your operation.

    private static void ManualAsyncOperation()
            {
    
                Task task = Task.Factory.StartNew(() =>
                    {
                        Console.WriteLine("Accessing database .....");
                        //Mimic the DB operation 
                        Thread.Sleep(1000);
    
                        return "Hello wolrd";
                    },TaskCreationOptions.LongRunning);
    
                var awaiter =task.GetAwaiter();
                awaiter.OnCompleted(() =>
                    {
                        try
                        {
                            var result = awaiter.GetResult();
    
                            Console.WriteLine("Result: {0}", result);
                        }
                        catch (Exception exception)
                        {
    
                            Console.WriteLine("Exception: {0}",exception);
                        }
                    });
                Console.WriteLine("Continuing on the main thread and waiting for the result ....");
                Console.WriteLine();
    
                Console.ReadLine();
    
            }
    

提交回复
热议问题