home screen

Search



Number Of Result : 0

Result :


Friday, November 21, 2008

Tạo 1 Thread bằng Delegate

- Thay vì trước đây chúng ta tạo 1 Thread bằng cách new 1 Thread và Start Thread đó. Lần này chúng ta sẽ tạo 1Thread bằng Delegate
- Ta ví dụ 1 Thread Delegate(tạo bời Delegate) và 1 Thread Main(trong hàm Main)

- 1. 2 Thread se thực hiện xen kẽ nhau ( lưu ý vị trí đặt của hàm EndInvoke ):

public delegate bool GeneralDelegate(int i, string str);
static void Main(string[] args)
{
GeneralDelegate delInstance = new GeneralDelegate(MyFunction);
IAsyncResult asyn = delInstance.BeginInvoke(100,
"I am in Delegate Thread", null, null);

for (int i = 0; i < 100; i++)
Console.WriteLine("I am in Main Thread {0}", i);

//ham EndInvoke dat sau for loop, do vay 2 thread nay se thuc hien xen ke nhau
bool status = delInstance.EndInvoke(asyn);

}
public static bool MyFunction(int count, string str)
{
for (int i = 0; i < count; i++)
Console.WriteLine(str + " {0}", i);
return true;
}


- 2. Thread Delegate thực hiện hoàn tất sau đó mới thực hiện Thread Main( lưu ý vị trí đặt của hàm EndInvoke )

public delegate bool GeneralDelegate(int i, string str);
static void Main(string[] args)
{
GeneralDelegate delInstance = new GeneralDelegate(MyFunction);
IAsyncResult asyn = delInstance.BeginInvoke(100,
"I am in Delegate Thread", null, null);
//chuyen ham EndInvoke trước tất cả các xử lý của Thread khác, khi đó nó sẽ thực hiện hoàn thành Thread Delegate xong thì mới thực hiện các Thread khac
bool status = delInstance.EndInvoke(asyn);

for (int i = 0; i < 100; i++)
Console.WriteLine("I am in Main Thread {0}", i);


}
public static bool MyFunction(int count, string str)
{
for (int i = 0; i < count; i++)
Console.WriteLine(str + " {0}", i);
return true;
}


- Check this function is put in Thread Background?

///
/// Nho dat trong actionItem
///

public byte[] exportToDoc()
{
//Neu nhu ko chay trong background(khac MainThread) -> la len
Debug.Assert(Thread.CurrentThread.IsBackground == true,"You must put this function in ActionItem");

//export
return null;

}

1 comment:

Tigger said...

Cái này gọi là, gọi hàm bất đồng bộ, thì dĩ nhiên nó cũng tạo ra một thread khác để thực thi cái hàm này :)