csharp-tricks
csharp-tricks
TDSec24- CSharp-Tricks
1 post
Don't wanna be here? Send us removal request.
csharp-tricks ยท 10 months ago
Text
How to log the call stack?
Console.WriteLine(new System.Diagnostics.StackTrace());
How to Implement try-catch within the function?
Let's implement a try-catch block within an asynchronous function. This is the solution to catch exceptions in asynchronous methods. Have a look at the following code. If you look closely inside the ShowAsync() function, then you will find we have implemented a try-catch within Task.run(). Within Task.run(), all processes are executed synchronously (in our example). So, if there is an exception, then it will be caught by the Exception Handling block.
using System; using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Asynchronious
{
class Test {
public Task ShowAsync() { return Task.Run(() => { try { Task.Delay(2000); throw new Exception("My Own Exception"); } catch (Exception ex) { Console.WriteLine(ex.Message); return null; } }); } public async void Call() { try { await ShowAsync(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } class Program { public static void Main(String [] args) { Test t = new Test(); t.Call(); Console.ReadLine(); } } }
0 notes