4

[免責事項 - このコードは読みやすいように (大幅に) 簡略化されており、通常のコード標準に準拠していないことがわかっています]

私の問題は、以下のコードで見ることができます。基本的に、オブジェクトを解析する呼び出し元があります。サブコンポーネントの値に基づいた値を返す前に、サブコンポーネントが終了するまで待機する必要があります。これはイベントによって通知されます。

問題は次のとおりです。このような状況で推奨されるパターンは何ですか (もちろん、実際の解決策があれば大歓迎です)。

私は TaskCompletionSource などの周りでさまざまなことを試しましたが、(できれば) エレガントな解決策を見つけるには私の理解が遅れているのではないかと心配しています。お役に立てれば幸いです。

public class AsyncEventTest
{
    // This is performed one a single (UI) thread. The exception to this is
    // a.B that might - at the calling time - get a asycronious update from the backend.
    // The update is syncronized into the calling context so Task.Wait etc. will effectivly
    // deadlock the flow.
    public static string CallMe(A a)
    {
        if (a.B.State != State.Ready)
        {
            // wait for a.B.State == State.Ready ... but how ...
            // await MagicMethod() ???;
        }

        // only execute this code after a.b.State == State.Ready
        return a.B.Text;
    }
}

public class A
{
    public B B { get; set; }
}

public class B
{
    public State State { get; private set; }
    public event Action StateChanged;
    public string Text { get; }
}

public enum State { Ready, Working, }

編集 - 私が試したことの例

public class AsyncEventTest2
{
    public static string CallMe(A a)
    {
        return CallMe1(a).Result;
    }

    public async static Task<string> CallMe1(A a)
    {
        await CallMe2(a);
        return a.B.Text;
    }

    public static Task CallMe2(A a)
    {
        TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
        if (a.B.State != State.Ready)
        {
            a.B.StateChanged += () =>
                {
                    if (a.B.State == State.Ready)
                        tcs.SetResult(a.B.Text);
                };
        }
        else
        {
            tcs.SetResult(a.B.Text);
        }

        return tcs.Task;
    }
}
4

1 に答える 1

6

StateChangedイベントに登録して、を使用できTaskCompletionSourceます。

public static Task WaitForReady(this B b)
{
    TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
    Action handler = null;
    handler = () =>
    {
        if (b.State == State.Ready)
        {
            b.StateChanged -= handler;
            tcs.SetResult(null);
        }
    };

    b.StateChanged += handler;
    return tcs.Task;
}

ハンドラーが登録される前にイベントが発生した場合、競合が発生する可能性があることに注意してください。

于 2013-01-09T17:10:23.220 に答える