RequestProductPurchaseAsync 抛出“设置后无法更改线程模式”

RequestProductPurchaseAsync throws “Cannot change thread mode after it is set”

我正在使用 monogame 作为游戏框架,我正在尝试在 UWP-App 中实现应用内购买功能,当我调用 RequestProductPurchaseAsync 时会抛出异常。它指出:

Cannot change thread mode after it is set. (Exception from HRESULT: 0x80010106 (RPC_E_CHANGED_MODE)) at Windows.ApplicationModel.Store.CurrentAppSimulator.RequestProductPurchaseAsync(String productId) at Crocs_World__Xbox_Edition_.App.d__7.MoveNext()

这就是我在代码中所做的事情:

public async Task LoadInAppPurchaseProxyFileAsync()   
{
     StorageFolder proxyDataFolder = await Package.Current.InstalledLocation.GetFolderAsync("data");
     StorageFile proxyFile = await proxyDataFolder.GetFileAsync("in-app-purchase.xml");
     licenseChangeHandler = new LicenseChangedEventHandler(InAppPurchaseRefreshScenario);
     CurrentAppSimulator.LicenseInformation.LicenseChanged += licenseChangeHandler;
     await CurrentAppSimulator.ReloadSimulatorAsync(proxyFile);

    // setup application upsell message
    try
    {
        ListingInformation listing = await CurrentAppSimulator.LoadListingInformationAsync();
        var product1 = listing.ProductListings["product1"];
        var product2 = listing.ProductListings["product2"];               
    }
    catch (Exception e)
    {
        Debug.WriteLine("LoadListingInformationAsync API call failed:" + e);               
    }
}

private async void InAppPurchaseRefreshScenario()
{           
    Debug.WriteLine("InAppPurchaseRefreshScenario");
}

public async Task BuyFeature()
{
    LicenseInformation licenseInformation = CurrentAppSimulator.LicenseInformation;
    if (!licenseInformation.ProductLicenses["product2"].IsActive)
    {
        Debug.WriteLine("Buying Product 2...");
        try
        {
            await CurrentAppSimulator.RequestProductPurchaseAsync("product2");
            if (licenseInformation.ProductLicenses["product2"].IsActive)
            {
                Debug.WriteLine("You bought Product 2.");
            }
            else
            {
                Debug.WriteLine("Product 2 was not purchased.");
            }
        }
        catch (Exception e)
        {
            Debug.WriteLine("Unable to buy Product 2." + e);
        }
    }
    else
    {
        Debug.WriteLine("You already own Product 2.");
    }
}

每当我调用 BuyFeature 时,它都会抛出异常。除非我在 LoadInAppPurchaseProxyFileAsync 中正确调用它。然后我猜它似乎在同一个线程中。 如果我在这两种方法中将 Task 替换为 void,它也不起作用。如果我从 app.xaml.cs 或 game.cs 调用它也没关系。 有人知道我做错了什么吗?

谢谢,

哈利

您必须在 UI 线程中调用 await CurrentAppSimulator.RequestProductPurchaseAsync(...),因为如果您 运行 它处于 await CurrentApp.RequestProductPurchaseAsync(...) 的发布模式,它会显示 "Buy item" 内容屏幕上的对话框,仅在 UI 线程中才有可能。

await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
    await CurrentAppSimulator.RequestProductPurchaseAsync("product2");
};