Program.cs 1.82 KB
Newer Older
Uwe Wienkop's avatar
Uwe Wienkop committed
1 2 3 4 5 6 7 8 9 10 11 12
using System;
using System.Threading;

namespace _06Exceptions_Threads
{
    public class ServerClass
    {

        static int count = 0;
        // The method that will be called when the thread is started.
        public void InstanceMethod()
        {
Uwe Wienkop's avatar
Uwe Wienkop committed
13
            int processNr = count++;
Uwe Wienkop's avatar
Uwe Wienkop committed
14 15 16 17 18 19
            try
            {
                Console.WriteLine("   InstanceMethod läuft in einem eigenen Thread");

                // Pause for a moment to provide a delay to make
                // threads more apparent.
Uwe Wienkop's avatar
Uwe Wienkop committed
20
                if (processNr == 3)
Uwe Wienkop's avatar
Uwe Wienkop committed
21 22 23 24 25 26 27 28 29
                {
                    Thread.Sleep(2000);
                    throw new NullReferenceException("Null Referenz!!!");
                }
                else
                    Thread.Sleep(3000);
            }
            catch (Exception e)
            {
Uwe Wienkop's avatar
Uwe Wienkop committed
30
                Console.WriteLine($"!!!Fehler {e.Message} in Instanz {processNr}");
Uwe Wienkop's avatar
Uwe Wienkop committed
31 32 33
            }
            finally
            {
Uwe Wienkop's avatar
Uwe Wienkop committed
34
                Console.WriteLine($"   Thread {processNr} wurde beendet");
Uwe Wienkop's avatar
Uwe Wienkop committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
            }
        }
    }

    public class Simple
    {
        public static void Main()
        {
            try
            {
                for (int i = 0; i < 10; i++)
                    CreateThreads();
                Console.WriteLine("Alle Threads gestartet!");
            }
            catch (Exception e)
            {
                Console.WriteLine($"Fehler: {e.Message}");
            }
            Console.WriteLine("Main() Ende");
        }
        public static void CreateThreads()
        {
            ServerClass serverObject = new ServerClass();

            Thread InstanceCaller = new Thread(new ThreadStart(serverObject.InstanceMethod));
            InstanceCaller.Start();  // Start the thread.

            Console.WriteLine("Ein neuer Thread wurde aus Main() gestartet");
        }
    }
}