非同期読取り

行を非同期に読み取るには、store.SearchAsync()またはstore.SearchByIndexAsync()を使用します。非同期に読み取る場合、読取り関数はただちにコントロールを返し、他の処理を続行できますが、読取り操作はバックグラウンドで実行されます。非同期読取り操作の開始からその完了までの時間を使用すると、役に立つ操作を実行できます。

この非ブロック・メカニズムは、出力を非同期に受信するメカニズムを提供するクラスにIObserverインタフェースを実装することによって実現できます。このクラスは、出力の受信および処理のために、次のコールバック関数をオーバーライドします。

  • void OnNext(IRow) — この関数は、表から行が読み取られるたびに起動されます。

  • void OnCompleted() — この関数は、非同期読取り操作の完了後に起動されます。

  • void OnError(Exception) — 非同期読取り操作中に例外が発生した場合、この関数が起動されます。

次のコード例は、サブスクライバの基本実装を示しています。

//the following class overrides the callback functions
class AsyncSubscriber : IObserver<IRow>
{
	// driver calls back for each result
	public void OnNext(IRow value)
	{
		Console.WriteLine("Received search result:" + value.ToJSONString());
	}
	
	// driver calls back when search completes
	public void OnCompleted()
	{
		Console.WriteLine("Search complete...");
	}
	
	// driver calls back if an error occurs
	public void OnError(Exception error)
	{
		Console.WriteLine("Error receiving search results...");
		Console.WriteLine(error.StackTrace);
	}
}

非同期読取り操作を実行するには、IObserverインタフェースを実装し、コールバック関数をオーバーライドするクラスのオブジェクトを作成します。次に、store.SearchAsync()でコールバック・クラス・オブジェクトをパラメータとして使用し、非同期読取り操作を起動します。

たとえば、複数の表の行の読取りに示すすべての行を読み取るためのコード・フラグメントは、次の方法で非同期読取りを使用するようにリライトできます。

public static void getAllRowsAsync(IKVStore store, String tableName)
{
	var row = store.CreateRow(tableName);
	//an object of the class overriding the callback functions is created
	AsyncSubscriber asyncsubscriber = new AsyncSubscriber();
	//the callback class object is used as the parameter
	store.SearchAsync(row, null, asyncsubscriber);
}

前述の例ではすべての行を取得します。結果を制限するには、同期検索と同様に、検索キーとして行を指定する必要があります。複数の表の行の読取りを参照してください。

同様に、索引を使用した読取りに示すコード・フラグメントは、次の方法で非同期読取りを使用するようにリライトできます。

public static void readUsingIndexesAsync(IKVStore store)
{
	String tableName = "student_data";
	var row = store.CreateRow(tableName);
	// an object of the class overriding the callback functions is created
	AsyncSubscriber asynsubscriber = new AsyncSubscriber();
	FetchOptions fetchoptions = new FetchOptions();            
	
	// BLOCK 1:
	// Uncomment this block to look up only table rows with a 
	// dateOfBirth field set to "1997-02-27". If this
	// block and BLOCK 2 are both used, then the result set 
	// will be empty.
	//row["dateOfBirth"] = "1997-02-27";

	// BLOCK 2:
	// This field range restricts the results set to only
	// those rows with a dateOfBirth field value between
	// "1996-01-01" and "1997-12-31", inclusive. 
	fetchoptions.FieldRange.FieldName = "dateOfBirth";
	fetchoptions.FieldRange.StartValue = "1996-01-01";
	fetchoptions.FieldRange.StartIsInclusive = true;
	fetchoptions.FieldRange.EndValue = "1997-12-31";
	fetchoptions.FieldRange.EndIsInclusive = true;
	
	// "dob" is the name of the index 
	// the callback class object is used as the parameter
	store.SearchByIndexAsync(row, "dob", fetchoptions, AsyncSubscriber);
}