闲来无事,捯饬一下C#
编译脚本:
@echo off
set PATH=C:\Windows\Microsoft.NET\Framework\v4.0.30319;%PATH%
echo "compile c# use csc cmd tool"
csc /t:exe /out:demo.exe csDemo.cs Person.cs SynchronThread.cs
::csc /t:library /r:System.Web.dll /out:demo.dll Person.cs csDemo.cs
pause
demo.exe
pause
主函数:
using System;
using Stage1;
namespace Stage1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello c#!!!");
Person zhangsan = new Person();
zhangsan.name = "zhangsan";
zhangsan.age = 18;
zhangsan.say();
//线程测试!!!
SynchronThread hthread = new SynchronThread();
hthread.startThread();
}
}
}
格式类:
using System;
namespace Stage1
{
public class Person
{
public string name;
public int age;
public void say()
{
string message = string.Format("name=({0}), age=({1})", name, age);
System.Console.WriteLine(message);
System.Console.WriteLine("my name is {0}, {1:d2} old, time:{2 :dd/MM/yyyy}!", name, age, System.DateTime.Now);
System.Console.WriteLine("{0,10:d3} old!", age);//对齐10,长度3不足补0
}
}
}
线程类:
using System;//Console
using System.Collections.Generic;//List
using System.Threading;//Thread
class SynchronThread
{
public void startThread()
{
childref = new ThreadStart(SynchronThread.ThreadFunc);
Console.WriteLine("In main thread....ManagedThreadId={0}", Thread.CurrentThread.ManagedThreadId);
//
childThread_1 = new Thread(childref);
childThread_2 = new Thread(SynchronThread.ThreadFunc);
//
if (null != childThread_1 && null != childThread_2)
{
childThread_1.Start();
childThread_2.Start();
//
list_students.Add("zhangsan");
list_students.Add("lisi");
list_students.Add("wangwu");
Console.ReadKey();
}
}
public static void ThreadFunc()
{
Monitor.Enter(Lock);
//lock(Lock)
{
for (int i=0; i<10; i++)
{
count += 1;
Console.WriteLine("In Child thread...., ManagedThreadId={0}, count = {1}", Thread.CurrentThread.ManagedThreadId.ToString() , count);
}
for(int i=0; i<list_students.Count;i++)
{
Console.WriteLine("In Child thread...., student name={0}", list_students[i]);
}
foreach(string name in list_students)
{
Console.WriteLine("In Child thread...., student name={0}", name);
}
}
Monitor.Exit(Lock);
}
private ThreadStart childref;
private Thread childThread_1;
private Thread childThread_2;
//
private static List<string> list_students = new List<String>();
private static int count = 0;
private static readonly object Lock = new object();
}
运行结果: