ZengCode.Com (The Thai Php Framework)  


Home   Download   Manual   About us  

MAIN MENU
News
Php Tips
Android Programming
Design Pattern By PHP
Linux Quick Tips
C# using Linq น่าใช้จริงๆ
C# Tips & Technique
Java & JavaScript Tips
Database
ZengCode Framework Guide
Zeng Code Code
Programming
IPhone (Tips and Trick)

 

     Thread Synchronization (C# Programming Guide)  (2010-02-05)

นำไปประยุกต์ใช้กับ  multithreaded applications ในการเข้าถึง resources ที่ใช้ร่วมกันแบบง่ายๆ ก่อนนะครับ

อันแรกใช้ Lock Statement ครับ

For example:

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

namespace SyncronizeThread
{

class Program
{
public static Int32 counter = new Int32();
static System.Object myLock = new object();
private static Mutex mut = new Mutex();

static void Main(string[] args)
{

counter = 1;
Thread t = new Thread(Run);
t.Name = "a";
t.Start();
t = new Thread(Run);
t.Name = "b";
t.Start();
t = new Thread(Run);
t.Name = "c";
t.Start();

Console.ReadKey();
}

public static void Run()
{
Console.WriteLine(Thread.CurrentThread.Name + " Starting ");
lock (myLock)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(Thread.CurrentThread.Name + "===>" + (counter++));
Thread.Sleep(500);
}
}

}
}
}
อีกอันนึงใช้ mutex using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SyncronizeThread
{

class Program
{
public static Int32 counter = new Int32();
static System.Object myLock = new object();
private static Mutex mut = new Mutex();

static void Main(string[] args)
{

counter = 1;
Thread t = new Thread(Run);
t.Name = "a";
t.Start();
t = new Thread(Run);
t.Name = "b";
t.Start();
t = new Thread(Run);
t.Name = "c";
t.Start();

Console.ReadKey();
}

public static void Run()
{
Console.WriteLine(Thread.CurrentThread.Name + " Starting ");
mut.WaitOne();
for (int i = 0; i < 10; i++ )
{
Console.WriteLine(Thread.CurrentThread.Name + "===>" + (counter++));
Thread.Sleep(500);
}
mut.ReleaseMutex();

}
}
} อันนี้ใช้ Semaphore using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace SyncronizeThread
{

class Program
{
public static Int32 counter = new Int32();
static System.Object myLock = new object();
private static Mutex mut = new Mutex();
static Semaphore s = new Semaphore(2, 2);

static void Main(string[] args)
{

counter = 1;
Thread t = new Thread(Run);
t.Name = "a";
t.Start();
t = new Thread(Run);
t.Name = "b";
t.Start();
t = new Thread(Run);
t.Name = "c";
t.Start();

Console.ReadKey();
}

public static void Run()
{
Console.WriteLine(Thread.CurrentThread.Name + " Starting ");
s.WaitOne();
for (int i = 0; i < 10; i++ )
{
Console.WriteLine(Thread.CurrentThread.Name + "===>" + (counter++));
Thread.Sleep(500);
}
s.Release();

}
}
}

ผลการรันด้วย Lock Statement

a Starting
a===>1
b Starting
c Starting
a===>2
a===>3
a===>4
a===>5
a===>6
a===>7
a===>8
a===>9
a===>10
c===>11
c===>12
c===>13
c===>14
c===>15
c===>16
c===>17
c===>18
c===>19
c===>20
b===>21
b===>22
b===>23
b===>24
b===>25
b===>26
b===>27
b===>28
b===>29
b===>30

ผลการรันด้วย Mutex

a Starting
a===>1
b Starting
c Starting
a===>2
a===>3
a===>4
a===>5
a===>6
a===>7
a===>8
a===>9
a===>10
c===>11
c===>12
c===>13
c===>14
c===>15
c===>16
c===>17
c===>18
c===>19
c===>20
b===>21
b===>22
b===>23
b===>24
b===>25
b===>26
b===>27
b===>28
b===>29
b===>30

ผลการรันด้วย Semaphore

a Starting
a===>1
c Starting
c===>2
b Starting
a===>3
c===>4
a===>5
c===>6
a===>7
c===>8
a===>9
c===>10
a===>11
c===>12
a===>13
c===>14
a===>15
c===>16
a===>17
c===>18
a===>19
c===>20
b===>21
b===>22
b===>23
b===>24
b===>25
b===>26
b===>27
b===>28
b===>29
b===>30


จะเห็นว่าสามารถเข้าใช้งานตัวแปร counter (resouce)ได้พร้อมกัน สอง thread
 

จะเห็นว่า Lock กับ Mutext  thread จะใช้ resource ได้ทีละ thread, ต่างกันตรง Mutex มี scope การทำงานข้าม Process ได้
โดยระบุชื่อของ mutex เช่น  Mutex mut = new Mutex(false, "mutexName");
แต่ Lock จำกัดอยู่ใน Process เดียวเท่านั้น ส่วน Semaphore ระบุจำนวน thread ที่จะเข้ามาใช้ resource ได้ครับ สุดยอดไปเรยยยยยยย

บทความที่น่าสนใจ www.c-sharpcorner.com/UploadFile/mmehta/Multithreading311162005045743AM/Multithreading3.aspx

 

Thread State Diagram

[ThreadState Diagram]

 

 

 


Comment

Writing Binary Files   (08 กุมภาพันธ์ 2553)   
IP : 124.122.149.76

Writing Binary Files :

For files

with known internal structures the BinaryReader and BinaryWriter classes offer streaming functionality that's oriented towards particular data types. The good thing about writing binary files are you cannot read the files by just opening them in the notepad also binary files can be of very large size. Lets look at the code to create Binary files.

private void Button1_Click(object sender System.EventArgs e)
{
          FileStream  fs = File.Create(Server.MapPath("test.dat"));
    BinaryWriter bw = new BinaryWriter(fs); 

    int x = 10; 
    decimal d = 3.234M; 
    string str = "Hello World"; 

    bw.Write(x); 
    bw.Write(d); 
    bw.Write(str); 

    bw.Close(); 
    fs.Close(); 
}

nks>nks>

Okay now lets see what's happening in the code:

  1. First we made the FileStream object but in this case we are writing the .dat file which means the data file.
  2. We created an object of the BinaryWriter class.
  3. Later we declared three variables of type int decimal and string.
  4. Finally we wrote the three variables in the binary file.

If you go and see the file and try to open the file in notepad you will only see some strange characters. In other words you won't be able to see the text.

Reading Binary Files :

Lets see how we can read the Binary files.   

private void Button1_Click(object sender System.EventArgs e)
{
FileStream fs = File.OpenRead(Server.MapPath("test.dat"));
BinaryReader br = new BinaryReader(fs);

Response.Write(br.ReadInt32());
Response.Write(br.ReadDecimal());
Response.Write(br.ReadString());

br.Close();
fs.Close();
}

As you can see the Reading code for Binary Files is also very simple. If you have noticed the code is a bit different from which we saw earlier for reading Text files. Here we are extracting the data types that we wrote in the binary file. We use ReadInt32() method to read the integer out from the binary file. We use ReadDecimal() to read the decimal values from the binary file and so on. 

Refer these links for Reading and Writing Text Files and xml File operations.

 

ript type="text/javascript"> ript> ript src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> ript> ript type="text/javascript">google_protectAndRun("ads_core.google_render_ad" google_handleError google_render_ad);ript>

rame scrolling="no" height="250" frameborder="0" width="250" vspace="0" style="left: 0pt; position: absolute; top: 0pt;" src="http://googleads.g.doubleclick.net/pagead/ads?client=ca-pub-4333758194399401&output=html&h=250&slotname=5534717556&w=250&lmt=1265635586&flash=10.0.32&url=http%3A%2F%2Fwww.codersource.net%2Fcsharp_read_write_binary_files.html&dt=1265703949705&prev_slotnames=7271474921%2C7531215075&correlator=1265703949298&frm=0&ga_vid=1772583462.1265703949&ga_sid=1265703949&ga_hid=1097545893&ga_fc=0&u_tz=-720&u_his=1&u_java=0&u_h=800&u_w=1280&u_ah=770&u_aw=1280&u_cd=32&u_nplug=24&u_nmime=83&biw=1264&bih=597&ref=http%3A%2F%2Fwww.google.co.th%2Furl%3Fsa%3Dt%26source%3Dweb%26ct%3Dres%26cd%3D5%26ved%3D0CBsQFjAE%26url%3Dhttp%253A%252F%252Fwww.codersource.net%252Fcsharp_read_write_binary_files.html%26rct%3Dj%26q%3Dc%2523%2Bconversion%2Bbetween%2Bstring%2Bto%2Bbinary%2Bfile%26ei%3D9RBwS5NVzIuQBbuzudQH%26usg%3DAFQjCNEfc5Xse1vGTSdHBcJkMvDtWU8kYQ&fu=0&ifi=3&dtd=10&xpc=wyPbP43OSO&p=http%3A//www.codersource.net" name="google_ads_frame" marginwidth="0" marginheight="0" id="google_ads_frame3" hspace="0" allowtransparency="true">rame>


Name
Comment
Security CodeCAPTCHA Image

easy tracking
avis car rental discount code

This page took 0.079538 seconds to load.