我正在尝试从多线程程序访问Microsoft Store。该程序本身运行良好-那里没有问题,但是方法
Windows.Foundation.IAsyncOperation<StorePurchaseResult> purchase = product.RequestPurchaseAsync();
引发异常:
“无效的窗口句柄。\ r \ n \ r \ n必须从UI调用此函数线程“
我的代码如下...
private void testButton_Click(object sender, EventArgs e)
{
//Dispatcher dispUI = Dispatcher.CurrentDispatcher;
//dispUI.BeginInvoke((ThreadStart)delegate ()
//{
// _ = SetStore();
//});
//Dispatcher.BeginInvoke(new Action(TestStuff));
_ = SetStore();
}
[ComImport]
[Guid("4AEEEC08-7C92-4456-A0D6-1B675C7AC005")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IInitializeWithWindow
{
void Initialize(IntPtr hwnd);
}
private async Task SetStore()
{
try
{
StoreContext theStore = StoreContext.GetDefault();
// "Unable to cast object of type 'Windows.Services.Store.StoreContext' to type 'IInitializeWithWindow'."
// IInitializeWithWindow initWindow = (IInitializeWithWindow)(object)theStore;
// initWindow.Initialize(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle);
StoreProductResult app = await theStore.GetStoreProductForCurrentAppAsync();
// This works...
StoreProduct product = app.Product;
string title = product.Title;
string price = product.Price.FormattedPrice;
// This works...
StoreAppLicense license = await theStore.GetAppLicenseAsync();
bool trial = license.IsTrial;
bool full = license.IsActive;
// "Invalid window handle.\r\n\r\nThis function must be called from a UI thread"
StorePurchaseResult result = await theStore.RequestPurchaseAsync("9NRFBVGVGW8K");
// "Invalid window handle.\r\n\r\nThis function must be called from a UI thread"
// Windows.Foundation.IAsyncOperation<StorePurchaseResult> purchase = product.RequestPurchaseAsync();
}
catch (Exception e)
{
int a = 1;
}
}
我已将VS2019 UWP安装程序项目与商店相关联,我认为这就是为什么其他方法无需使用IInitializeWithWindow强制转换商店对象即可返回正确答案的原因(这也会引发错误,但绕过似乎使代码工作)。
我想我必须以某种方式进入UI线程-不知道如何。来自各地的各种示例似乎对我不起作用。谁能帮我吗?
对于UWP,您需要使用以下代码来调用UI线程:
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {
//UI code here
});