複製鏈接
請複製以下鏈接發送給好友

Yield

(編程術語)

鎖定
Yield的功能將控制權轉移給其它圖形對象,包括非PowerBuilder對象。該函數檢測消息隊列,如果有消息,就把消息取出。利用該函數可以在執行耗時較長的操作時把控制權轉讓給其它應用。
外文名
Yield
返回值
Boolean
形    式
yield return ;
在 iterator
用作方法、運算符或訪問器的體

目錄

Yield語法

Yield( )
Boolean返回值。如果在消息隊列中提取到了消息,那麼函數返回TRUE,否則返回FALSE。用法正常情況下,PowerBuilder應用程序在執行一段代碼(比如函數或事件處理程序)的過程中不響應用户的操作。對耗時短暫的代碼段來説,這種處理方式沒有什麼不妥的地方,但是,如果某個代碼段的執行耗時較長,應用程序又希望為用户提供更多的控制權,那麼需要在這段代碼中插入Yield( )函數,讓用户能夠進行其它操作,特別在循環執行的代碼中更應該如此。應用程序執行Yield( )函數後,如果發現消息隊列中存在消息,它將允許對象處理這些消息,處理之後,繼續Yield( )函數後面代碼的執行。因此,代碼中插入Yield( )函數將降低應用程序的運行效率。
---------------------------------------------------------------------------------------------------------------------------------------------------------
yield(C# 參考)
迭代器塊中用於向枚舉數對象提供值或發出迭代結束信號。它的形式為下列之一:
yield return <expression>;
yield break;
備註 :
計算表達式並以枚舉數對象值的形式返回;expression 必須可以隱式轉換為迭代器的 yield 類型。
yield 語句只能出現在 iterator 塊中,該塊可用作方法、運算符或訪問器的體。這類方法、運算符或訪問器的體受以下約束的控制:
不允許不安全塊。
方法、運算符或訪問器的參數不能是 ref 或 out。
yield 語句不能出現在匿名方法中。
當和 expression 一起使用時,yield return 語句不能出現在 catch 塊中或含有一個或多個 catch 子句的 try 塊中。
在下面的示例中,迭代器塊(這裏是方法 Power(int number,int power) )中使用了 yield 語句。當調用 Power 方法時,它返回一個包含數字冪的可枚舉對象。注意 Power 方法的返回類型是 IEnumerable(一種迭代器接口類型)。

Yield例子

C#
public class List
{
//using System.Collections;
public static IEnumerable Power(int number,int exponent)
{
int counter = 0;
int result = 1;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}
static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach (int i in List.Power(2,8))
{
Console.Write("{0} ",i);
}
}
}
/*
Output:
2 4 8 16 32 64 128 256
*/
---------------------------------------------------------------------------------------------------------------------------------------------------------
JAVA例子
class OutputClass implements Runnable{
String name;
OutputClass(String s){
name=s;
}
public void run(){
for(int i=0;i<3;i++){
System.out.println(name);
Thread.yield();
}
}
}
public class RunThreads {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
OutputClass out1=new OutputClass("Thread1");
OutputClass out2=new OutputClass("Thread2");
Thread T1=new Thread(out1);
Thread T2=new Thread(out2);
T1.start();
T2.start();
}
}
/×説明:這裏創建了2個線程,運行結果如下:
Thread1
Thread2
Thread1
Thread2
Thread1
Thread2
×/
這裏不一定是交替運行的,有各種可能順序,但是他們一定都會執行。