如何从UI线程调用方法



我正试图从多线程程序访问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.rnrnThis function must be called from a UI thread" 
StorePurchaseResult result = await theStore.RequestPurchaseAsync("9NRFBVGVGW8K");

// "Invalid window handle.rnrnThis 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线程——不知道怎么做。来自各地的各种例子似乎对我不起作用。有人能帮我吗?

EDIT:这是一个带有UWP包装的.Net程序,用于创建MSIX包

对于UWP,您需要使用以下代码来调用UI线程:

await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {
//UI code here
});

试试下面的,它适用于.net 6 wpf应用

WinRT.Interop.InitializeWithWindow.Initialize(storeContext, new WindowInteropHelper(window).Handle);

最新更新