C#阻止功能和等待事件触发。还使用异步IAsyncOperation

时间:2016-09-16 14:14:21

标签: c# events asynchronous windows-runtime windows-store-apps

我目前在阻止某个功能并等待事件触发时遇到问题。以下是我的代码:

    bool isNotSwiped = true;
    bool isNotCancel = true;
    public Foo WaitForInputEvent(string strEventType, string PromptFor)
    {
        Foo ret = new Foo();

        MSR.MSR.Instance.Swipe += Instance_Swipe;

        while (isNotSwiped && isNotCancel)
        {
            Task.Run(async () => await Task.Delay(1000));
        }

        (ret as Foo).MSRData = SwipeData;

        return ret;
    }

    public Foo SwipeData { get; set; }

    private void Instance_Swipe(object sender, Windows.Devices.PointOfService.MagneticStripeReaderBankCardDataReceivedEventArgs e)
    {
        isNotSwiped = false;

        SwipeData = new Foo();

        (SwipeData as Foo).MSRData = CreateExtensibilityMagneticStripeReaderCardDataFromBankCard(e);

        MSR.MSR.Instance.Swipe -= Instance_Swipe;
    }
        (ret as Foo).MSRData = SwipeData;

        return ret;
    }

    public MSRInputEventArgs SwipeData { get; set; }

    private void Instance_Swipe(object sender, Windows.Devices.PointOfService.MagneticStripeReaderBankCardDataReceivedEventArgs e)
    {
        isNotSwiped = false;

        SwipeData = new MSRInputEventArgs();

        (SwipeData as MSRInputEventArgs).MSRData = CreateExtensibilityMagneticStripeReaderCardDataFromBankCard(e);

        MSR.MSR.Instance.Swipe -= Instance_Swipe;
    }

当我刷卡时,Instance_Swipe方法不会触发。可能是因为while循环。

我尝试使用async void并且它正常工作。但是,我还是想回归Foo。我们也在使用Windows Runtime,因此我们无法使用Task。以下是我尝试的另一个实验:

    private TaskCompletionSource<Foo> tcs = new TaskCompletionSource<Foo>();
    public async IAsyncOperation<Foo> WaitForInputEvent(string strEventType, string PromptFor)
    {
        Foo ret = new Foo();

        MSR.MSR.Instance.Swipe += Instance_Swipe;
        await tcs.Task;

        (ret as Foo).MSRData = LastSwipedData;

        IAsyncOperation<Foo> test = tcs.Task.AsAsyncOperation<Foo>();

        //cannot find correct cast / return here
        return test;
    }

问题是,我似乎找不到异步IAsyncOperation的正确返回类型,因此它不允许编译。我们在Instance_Swipe上触发任务完成源。

有人能推荐什么是最好的方法吗?这是一个通用Windows应用商店应用。

谢谢

1 个答案:

答案 0 :(得分:2)

async关键字必须Task / Task<T> / void返回类型一起使用。它不能与任何其他返回类型一起使用。

因此,要解决您的问题,您只需将代码拆分为两个方法:一个返回Task<T>并使用async,另一个返回IAsyncOperation<T>

private async Task<Foo> DoWaitForInputEventAsync(string strEventType, string PromptFor)
{
  Foo ret = new Foo();

  MSR.MSR.Instance.Swipe += Instance_Swipe;
  await tcs.Task;

  (ret as Foo).MSRData = LastSwipedData;

  return ret;
}

public IAsyncOperation<Foo> WaitForInputEvent(string strEventType, string PromptFor)
{
  return DoWaitForInputEventAsync(strEventType, PromptFor).AsAsyncOperation();
}