2010-11-19 5 views
1

WCFサービス用の非同期メソッドを簡単に作成したいと考えています。これを行う方法は、Begin/End非同期パターンを使用し、BeginメソッドにAsyncPattern = trueとラベルを付けることです。私は実際に自分自身のAsyncResultオブジェクトを処理する必要があるかどうか(私は少し心配しています)、またはイベントハンドラを使用して、Begin/EndをイベントハンドラのBegin/End呼び出し。これは、これを行う周りの方法のようですが、(限り私が知っている限り)WCFから直接イベントを呼び出すことはできません。それはもっともらしい解決策のようです。AsyncResultを作成するためにイベントを使用してBegin/End asyncパターンをショートカットできますか?

private event EventHandler<RequestEventArgs> OnSendRequest; 

[OperationContract(AsyncPattern = true)] // Borrowed from the interface for this example 
public IAsyncResult BeginSendRequest(Request request, AsyncCallback callback, object state) 
{ 
    EventHandler<RequestEventArgs> handler = OnSendRequest; 
    if (handler != null) 
     return handler.BeginInvoke(this, new RequestEventArgs(request), callback, handler); 
    return null; 
} 

public void EndSendRequest(IAsyncResult result) 
{ 
    EventHandler<RequestEventArgs> handler = (EventHandler<RequestEventArgs>)result.AsyncState; 
    handler.EndInvoke(result); 
} 

明らかに、何かがイベントを購読して作業を行います。また、Beginメソッドに渡されたオブジェクトの状態をスローして、イベントハンドラを状態として渡して、EndInvokeを呼び出すためのアクセス権を持っています。

これは実行可能なオプションですか? (私は、AsyncResultオブジェクトと非同期プログラミングが一般的にどのように機能するかに関する知識と知識が限られています)。

答えて

0

Checkout Reactive Extensions for .NET(Rx)。これはあなたが探しているパターンのan implementationです。

exampleを考える:

var client = new WebClient(); 
var searchUri = new Uri("http://search.twitter.com/search.json?q=4sq.com"); 
var uploadUri = new Uri("http://localhost:8080/uploads"); 

IObservable<Unit> query = 
    from result in client.DownloadStringAsObservable(searchUri, new object()) 
    let transformed = TransformResult(result) 
    from upload in client.UploadStringAsObservable(
     uploadUri, 
     "POST", 
     transformed, 
     new object()) 
    select upload; 

var subscription = query.Subscribe(
    x => {}, // Nothing to do 
    exn => 
    { 
     // Do something with the exception 
    }, 
    () => 
    { 
     // Indicate we're finished 
    }); 
+0

おかげで、それは私のプログラムに適用面白いではなくなります。 –

+0

どこでも実装されています。IObservable – AdamSane

+0

WCF接続をサポートしています。私はウェブサイトからダウンロードの例を掲示した。私は便利なWCFの例はありませんが、コードはほぼ同じです。 wcfクライアントオブジェクトを購読すると、(item、exception、finished)ハンドラが得られます。彼らはそれをjavascriptに移植しました。 – AdamSane

0

はい、私は開始/終了パターンと同じことをやっています。それは次のようになります。私は、JavaScriptのエンドポイントにWCFサービス/ WCFクライアントコールバックの実装ではなく、Webサービスをやっているよう

public IAsyncResult BeginInsertWorkOrder(Dictionary<String, String> workOrderData, AsyncCallback callBack, Object state) 
{ 
    Action<Dictionary<String, String>> command = new Action<Dictionary<String, String>>(InsertWorkOrder); 
    return command.BeginInvoke(workOrderData, callBack, command); 
} 
関連する問題