zoukankan      html  css  js  c++  java
  • C#学习笔记

    一:调用DLL

     1  //puts 函数的参数的默认封送处理从默认值 LPTSTR 重写为 LPSTR
     2  [DllImport("msvcrt.dll")]
     3  public static extern int puts([MarshalAs(UnmanagedType.LPStr)] string m);
     4  [DllImport("msvcrt.dll")]
     5  internal static extern int _flushall();
     6 
     7 
     8  // 如果没加 EntryPoint 的话 函数名必须和DLL中的函数名一致
     9  [DllImport("TestDLL.dll", EntryPoint = "fnTestDLL")]
    10  public static extern int abc([MarshalAs(UnmanagedType.LPStr)]string m);
    11 
    12  static void Main(string[] args)
    13  {
    14      abc("asd");
    15      puts("Hello World!");
    16      _flushall();
    17 
    18      Console.Read();
    19  }
    调用DLL例子
    
    

    二:线程

     1 public class Alpha
     2 {
     3     public void Beta()
     4     {
     5         while(true)
     6         {
     7             Console.WriteLine("Alpha.Beta is running in its own thread");
     8         }
     9     }
    10 };
    11 
    12 
    13 Alpha oAlpha = new Alpha();
    14 Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
    15 oThread.Start();
    16 while (!oThread.IsAlive) ;// 判断线程是否结束
    17 Thread.Sleep(1);            // 放弃时间片
    18 oThread.Abort();            // 关闭线程
    19 
    20 oThread.Join();              // 阻塞等待线程结束
    21 
    22 try
    23 {
    24     // 线程不允许重新启动
    25     Console.WriteLine("Try to restart the Alpha.Beta thread");
    26     oThread.Start();
    27 }
    28 catch(ThreadStateException)
    29 {
    30     Console.Write("ThreadStateException trying to restart Alpha.Beta. ");
    31     Console.WriteLine("Expected since aborted threads cannot be restarted.");
    32 }
    线程例子1
      1 public class CellProd
      2 {
      3     Cell cell;         // Field to hold cell object to be used
      4     int quantity = 1;  // Field for how many items to produce in cell
      5 
      6     public CellProd(Cell box, int request)
      7     {
      8         cell = box;          // Pass in what cell object to be used
      9         quantity = request;  // Pass in how many items to produce in cell
     10     }
     11     public void ThreadRun()
     12     {
     13         for (int looper = 1; looper <= quantity; looper++)
     14             cell.WriteToCell(looper);  // "producing"
     15     }
     16 }
     17 
     18 public class CellCons
     19 {
     20     Cell cell;         // Field to hold cell object to be used
     21     int quantity = 1;  // Field for how many items to consume from cell
     22 
     23     public CellCons(Cell box, int request)
     24     {
     25         cell = box;          // Pass in what cell object to be used
     26         quantity = request;  // Pass in how many items to consume from cell
     27     }
     28     public void ThreadRun()
     29     {
     30         int valReturned;
     31         for (int looper = 1; looper <= quantity; looper++)
     32             valReturned = cell.ReadFromCell();
     33     }
     34 }
     35 
     36 public class Cell
     37 {
     38     int cellContents;         // Cell contents
     39     bool readerFlag = false;  // State flag
     40     public int ReadFromCell()
     41     {
     42         lock (this)   // Enter synchronization block
     43         {
     44             if (!readerFlag)
     45             {
     46                 // Waits for the Monitor.Pulse in WriteToCell
     47                 Monitor.Wait(this);
     48             }
     49             Console.WriteLine("Consume: {0}", cellContents);
     50             readerFlag = false;    // Reset the state flag to say consuming is done.
     51 
     52             Monitor.Pulse(this);   // Pulse tells Cell.WriteToCell
     53 
     54 }   // Exit synchronization block
     55         return cellContents;
     56     }
     57 
     58     public void WriteToCell(int n)
     59     {
     60         lock (this)  // Enter synchronization block
     61         {
     62             if (readerFlag)
     63             {
     64                 Monitor.Wait(this);   // Wait for the Monitor.Pulse in
     65             }
     66             cellContents = n;
     67             Console.WriteLine("Produce: {0}", cellContents);
     68             readerFlag = true;    // Reset the state flag to say producing is done
     69 
     70             Monitor.Pulse(this);  // Pulse tells Cell.ReadFromCell
     71 
     72         }   // Exit synchronization block
     73     }
     74 
     75 
     76 
     77 
     78 int result = 0;   // Result initialized to say there is no error
     79 Cell cell = new Cell( );
     80 
     81 CellProd prod = new CellProd(cell, 20);  // Use cell for storage, 
     82 CellCons cons = new CellCons(cell, 20);  // Use cell for storage, 
     83 
     84 Thread producer = new Thread(new ThreadStart(prod.ThreadRun));
     85 Thread consumer = new Thread(new ThreadStart(cons.ThreadRun));
     86 
     87 try
     88 {
     89    producer.Start( );
     90    consumer.Start( );
     91 
     92    producer.Join( );   // Join both threads with no timeout
     93    consumer.Join( );  
     94 }
     95 catch (ThreadStateException e)
     96 {
     97    result = 1;            // Result says there was an error
     98 }
     99 catch (ThreadInterruptedException e)
    100 {
    101    result = 1;            // Result says there was an error
    102 }
    103 // Even though Main returns void, this provides a return code to the parent process.
    104 Environment.ExitCode = result;
    C# lock 关键字和 Monitor 对象的 Pulse 方法完成同步
     1 public class SomeState
     2 {
     3     public int Cookie;
     4     public SomeState(int iCookie)
     5     {
     6         Cookie = iCookie;
     7     }
     8 }
     9 
    10 public class Alpha
    11 {
    12     public Hashtable HashCount;
    13     public ManualResetEvent eventX;
    14     public static int iCount = 0;
    15     public static int iMaxCount = 0;
    16     public Alpha(int MaxCount)
    17     {
    18         HashCount = new Hashtable(MaxCount);
    19         iMaxCount = MaxCount;
    20     }
    21 
    22     public void Beta(Object state)
    23     {
    24         // Write out the hashcode and cookie for the current thread
    25         Console.WriteLine(" {0} {1} :", Thread.CurrentThread.GetHashCode(), ((SomeState)state).Coo
    26         // The lock keyword allows thread-safe modification of variables accessible across multipl
    27         Console.WriteLine("HashCount.Count=={0}, Thread.CurrentThread.GetHashCode()=={1}",
    28            HashCount.Count, Thread.CurrentThread.GetHashCode());
    29         lock (HashCount)
    30         {
    31             if (!HashCount.ContainsKey(Thread.CurrentThread.GetHashCode()))
    32                 HashCount.Add(Thread.CurrentThread.GetHashCode(), 0);
    33             HashCount[Thread.CurrentThread.GetHashCode()] =
    34                ((int)HashCount[Thread.CurrentThread.GetHashCode()]) + 1;
    35         }
    36 
    37         // Do some busy work.
    38         // Note: Depending on the speed of your machine, if you 
    39         // increase this number, the dispersement of the thread
    40         // loads should be wider.
    41         int iX = 2000;
    42         Thread.Sleep(iX);
    43         // The Interlocked.Increment method allows thread-safe modification
    44         // of variables accessible across multiple threads.
    45         Interlocked.Increment(ref iCount);  //**********
    46 
    47 
    48         if (iCount == iMaxCount)
    49         {
    50             Console.WriteLine();
    51             Console.WriteLine("Setting eventX ");
    52             eventX.Set();
    53         }
    54     }
    55 }
    56 
    57 
    58 
    59 bool W2K = false;
    60 int MaxCount = 10;
    61 
    62 ManualResetEvent eventX = new ManualResetEvent(false);    // Mark the event as unsignaled.
    63 Alpha oAlpha = new Alpha(MaxCount);
    64 
    65 // Make sure the work items have a reference to the signaling event.
    66 oAlpha.eventX = eventX;
    67 Console.WriteLine("Queue to Thread Pool 0");
    68 try
    69 {
    70   // 第二个参数是 作为 oAlpha.Beta 的参数
    71   ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta), new SomeState(0));
    72    W2K = true;
    73 }
    74 catch (NotSupportedException)
    75 {
    76    Console.WriteLine("These API's may fail when called on a non-Windows 2000 system.");
    77    W2K = false;
    78 }
    79 if (W2K)  // If running on an OS which supports the ThreadPool methods.
    80 {
    81    for (int iItem=1;iItem < MaxCount;iItem++)
    82    {
    83       // Queue the work items:
    84       Console.WriteLine("Queue to Thread Pool {0}", iItem);
    85       ThreadPool.QueueUserWorkItem(new WaitCallback(oAlpha.Beta),new SomeState(iItem));
    86    }
    87    Console.WriteLine("Waiting for Thread Pool to drain");
    88 
    89    // Wait until event is fired, meaning eventX.Set() was called:
    90    eventX.WaitOne(Timeout.Infinite,true);
    91    // The WaitOne won't return until the event has been signaled.
    92    Console.WriteLine("Thread Pool has been drained (Event fired)");
    93    Console.WriteLine(); Console.WriteLine("Load across threads");
    94    foreach(object o in oAlpha.HashCount.Keys)
    95       Console.WriteLine("{0} {1}", o, oAlpha.HashCount[o]);
    96 }
    线程池 与 ManualResetEvent 对象的使用
     1 static Mutex gM1;
     2 static Mutex gM2;
     3 const int ITERS = 100;
     4 static AutoResetEvent Event1 = new AutoResetEvent(false);
     5 static AutoResetEvent Event2 = new AutoResetEvent(false);
     6 static AutoResetEvent Event3 = new AutoResetEvent(false);
     7 static AutoResetEvent Event4 = new AutoResetEvent(false);
     8 
     9 
    10 
    11 public class MutexSample
    12 {
    13     public static void Main(String[] args)
    14     {
    15         Console.WriteLine("Mutex Sample ...");
    16         // Create Mutex initialOwned, with name of "MyMutex".
    17         gM1 = new Mutex(true, "MyMutex");
    18         // Create Mutex initialOwned, with no name.
    19         gM2 = new Mutex(true);
    20         Console.WriteLine(" - Main Owns gM1 and gM2");
    21 
    22         AutoResetEvent[] evs = new AutoResetEvent[4];
    23         evs[0] = Event1;    // Event for t1
    24         evs[1] = Event2;    // Event for t2
    25         evs[2] = Event3;    // Event for t3
    26         evs[3] = Event4;    // Event for t4
    27 
    28         MutexSample tm = new MutexSample( );
    29         Thread t1 = new Thread(new ThreadStart(tm.t1Start));
    30         Thread t2 = new Thread(new ThreadStart(tm.t2Start));
    31         Thread t3 = new Thread(new ThreadStart(tm.t3Start));
    32         Thread t4 = new Thread(new ThreadStart(tm.t4Start));
    33         t1.Start( );   // Does Mutex.WaitAll(Mutex[] of gM1 and gM2)
    34         t2.Start( );   // Does Mutex.WaitOne(Mutex gM1)
    35         t3.Start( );   // Does Mutex.WaitAny(Mutex[] of gM1 and gM2)
    36         t4.Start( );   // Does Mutex.WaitOne(Mutex gM2)
    37 
    38         Thread.Sleep(2000);
    39         Console.WriteLine(" - Main releases gM1");
    40         gM1.ReleaseMutex( );  // t2 and t3 will end and signal
    41 
    42         Thread.Sleep(1000);
    43         Console.WriteLine(" - Main releases gM2");
    44         gM2.ReleaseMutex( );  // t1 and t4 will end and signal
    45 
    46         // Waiting until all four threads signal that they are done.
    47         WaitHandle.WaitAll(evs); 
    48         Console.WriteLine("... Mutex Sample");
    49     }
    50 
    51     public void t1Start( )
    52     {
    53         Console.WriteLine("t1Start started,  Mutex.WaitAll(Mutex[])");
    54         Mutex[] gMs = new Mutex[2];
    55         gMs[0] = gM1;  // Create and load an array of Mutex for WaitAll call
    56         gMs[1] = gM2;
    57         Mutex.WaitAll(gMs);  // Waits until both gM1 and gM2 are released
    58         Thread.Sleep(2000);
    59         Console.WriteLine("t1Start finished, Mutex.WaitAll(Mutex[]) satisfied");
    60         Event1.Set( );      // AutoResetEvent.Set() flagging method is done
    61     }
    62 
    63     public void t2Start( )
    64     {
    65         Console.WriteLine("t2Start started,  gM1.WaitOne( )");
    66         gM1.WaitOne( );    // Waits until Mutex gM1 is released
    67         Console.WriteLine("t2Start finished, gM1.WaitOne( ) satisfied");
    68         Event2.Set( );     // AutoResetEvent.Set() flagging method is done
    69     }
    70 
    71     public void t3Start( )
    72     {
    73         Console.WriteLine("t3Start started,  Mutex.WaitAny(Mutex[])");
    74         Mutex[] gMs = new Mutex[2];
    75         gMs[0] = gM1;  // Create and load an array of Mutex for WaitAny call
    76         gMs[1] = gM2;
    77         Mutex.WaitAny(gMs);  // Waits until either Mutex is released
    78         Console.WriteLine("t3Start finished, Mutex.WaitAny(Mutex[])");
    79         Event3.Set( );       // AutoResetEvent.Set() flagging method is done
    80     }
    81 
    82     public void t4Start( )
    83     {
    84         Console.WriteLine("t4Start started,  gM2.WaitOne( )");
    85         gM2.WaitOne( );   // Waits until Mutex gM2 is released
    86         Console.WriteLine("t4Start finished, gM2.WaitOne( )");
    87         Event4.Set( );    // AutoResetEvent.Set() flagging method is done
    88     }
    89 }
    处理线程过程中使用 Mutex 类、AutoResetEvent 类和 WaitHandle 类
  • 相关阅读:
    Java_流程控制
    Java_循环
    Java_集合
    Java_泛型
    关于DTO的理解
    IDEA_Springboot启动Tomcat报错_APR
    canvas画圆又毛边
    关于数字加载的动画 jquery
    微信里关闭窗口 js
    依赖jquery的select皮肤2
  • 原文地址:https://www.cnblogs.com/gabo/p/4036183.html
Copyright © 2011-2022 走看看