Mittwoch, 8. Februar 2012, 15:24

Du bist nicht angemeldet.



ezazazel

The Supporter

  • »ezazazel« ist der Autor dieses Themas

Beiträge: 719

Ubuntu: 11.10

Kernel: 3.0.0-14-generic

Desktop: Gnome

Architektur: 32-bit

  • Private Nachricht senden

1

Montag, 10. September 2007, 21:10

C# / MONO Programm; Thread und Timer

Hier ein Beispiel wie man einen Thread erstellt, welcher einen Timer beinhaltet der in diesem läuft.
Also Thread wird erstellt. Dem Thread wird ein Timer zugewiesen welcher "." in Abstand von einer Sekunde schreibt.

Quellcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;

namespace Timer
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			//Schreibe eine Informationszeile
			Console.WriteLine("Program with Thread and Timer Ticks");

			//Erstelle einen Thread welcher ThreadProc startet
			System.Threading.Thread bgthrd = 
				new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
			
			//Starten des Threads
			bgthrd.Start();
			
			//Warten auf weitere Eingaben
			Console.ReadLine();
		}
		
		//Methode welche als extra Thread aufgerufen wird
		private static void ThreadProc()
		{
			//Erstellen eines Timers
			System.Timers.Timer t = new System.Timers.Timer(1000);
			
			//Weist eine Methode zu, welche ausgeführt wird wenn der Timer tickt
			t.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Tick);
			
			//Starten des Timers
			t.Start();
		}
		
		//Methode welche bei Tick aufgerufen wird
		private static void Timer_Tick(object sender, System.Timers.ElapsedEventArgs e)
		{
			//Schreiben von "." in der Konsole
			Console.Write(".");
		}
	}
}


und hier ohne Kommentare:

Quellcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using System;

namespace Timer
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("Program with Thread and Timer Ticks");

			System.Threading.Thread bgthrd = 
				new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
			
			bgthrd.Start();
			Console.ReadLine();
		}
		
		private static void ThreadProc()
		{
			System.Timers.Timer t = new System.Timers.Timer(1000);
			t.Elapsed += new System.Timers.ElapsedEventHandler(Timer_Tick);
			t.Start();
		}
		private static void Timer_Tick(object sender, System.Timers.ElapsedEventArgs e)
		{
			Console.Write(".");
		}
	}
}
»ezazazel« hat folgende Datei angehängt:
  • Timer.tar.gz (3,57 kB - 175 mal heruntergeladen - zuletzt: 2. Januar 2012, 16:04)
Si non confectus, non reficiat (If it's not broken, don't fix it)
Shuttle XPC SD39P2; Intel Core2Duo 6420; Samsung T166 SATA II 3,5" 500GB; Gainward Bliss 8600GT PCX SilentFx, Cinergy T USB XS hybrid && MSI Wind Nettop && Toshiba Portege M700 && Acer Aspire One