C#多线程学习笔记(一)

a.在C#中要使用线程要引用System.Threading;

using System.Threading;

b.在C#可以对程进行命名

Thread _thrd = new Thread(new ThreadStart());
_thrd.Name 
= "thisthrd.name"

c.可以通过Thread的static属性获取当前线程
Thread.CurrentThread

d.操作线程的几个重要的方法

Start():启动线程
Sleep(int):静态方法,暂停当前线程指定的毫秒数
Abort():通常使用该方法来终止一个线程
Suspend():该方法并不终止未完成的线程,它仅仅挂起线程,以后还可恢复。
Resume():恢复被Suspend()方法挂起的线程的执行

e. sample

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ThreadOperation
{
    
public class Alpha
    
{
        Int32 i;
        
public Alpha()
        
{
            i 
= 0;
        }

        
public void Beta()
        
{
            
while (true)
            
{
                Console.WriteLine(i.ToString() 
+ ":Alpha.Beta is running out of its own thread");
                i
++;
            }

        }

    }


    
class Program
    
{
        
static int Main(string[] args)
        
{
            Thread.CurrentThread.Name 
= "System Thread";
            Console.WriteLine(
"Thread Start/Stop/Join sample");
            Alpha oAlpha 
= new Alpha();
            Thread oThread 
= new Thread(new ThreadStart(oAlpha.Beta));
            oThread.Start();
            oThread.Name 
= "Alpha Thread";
            
while (!oThread.IsAlive) Console.WriteLine("has dead");
            Console.WriteLine(
"Current Thread:" + Thread.CurrentThread.Name);
            Thread.Sleep(
1);
            Console.WriteLine(
"oThread.ThreadState:"+oThread.ThreadState);
            oThread.Abort();
            Console.WriteLine(
"oThread.ThreadState:" + oThread.ThreadState);
            oThread.Join();
            Console.WriteLine(
"oThread.ThreadState:" + oThread.ThreadState);
            Console.WriteLine();
            Console.WriteLine(
"Alpha.Beta has finished");
            
try
            
{
                Console.WriteLine(
"Try to restart the Alpha.Beta thread");
                oThread.Start();
            }

            
catch (ThreadStateException)
            
{
                Console.WriteLine(
"oThread.ThreadState:" + oThread.ThreadState);
                Console.Write(
"ThreadStateException trying to restart Alpha.Beta. ");
                Console.WriteLine(
"Expected since aborted threads cannot be restarted.");
                Console.ReadLine();
            }

            
return 0;

            
        }

    }

}

posted on 2008-06-21 23:25  dinglin2006  阅读(235)  评论(0编辑  收藏  举报

导航