gpt4 book ai didi

c# - 如何正确使用 Dispatcher.BeginInvoke?

转载 作者:太空狗 更新时间:2023-10-30 01:21:21 25 4
gpt4 key购买 nike

我几乎在互联网上到处搜索,我用谷歌搜索了很多次,找到了很多结果,但我仍然找不到解决我问题的方法。

我正忙于将旧的 WinForms 应用程序转换为新的 WPF 应用程序,但我在使用某些命令时遇到了问题。在 Winforms 应用程序中,他们使用 Control.BeginInvoke() 并将其存储在 IAsyncResult 对象中。我读到 Dispatcher.BeginInvoke()WPF 等同于 WinFormsControl.BeginInvoke() > 但是当我使用

时出现这个错误

Dispatcher.BeginInvoke(): "Cannot implicitly convert type 'System.Windows.Threading.DispatcherOperation' to 'System.IAsyncResult'. An explicit conversion exists (are you missing a cast?)".

我们将不胜感激。

这是我要转换的代码。这是原始的 WinForms 代码。我能够转换除 BeginInvoke 部分以外的所有内容。

    private eSkan.api.TeSkanAPI feSkanAPI = null;

private void MessageFilter_AddRemove_Invoked(bool AddFilter, IMessageFilter Filter)
{
if (AddFilter){ Application.AddMessageFilter(Filter); }
else { Application.RemoveMessageFilter(Filter); }
}

private void MessageFilter_AddRemove(bool AddFilter, IMessageFilter Filter)
{
{
IAsyncResult sr = BeginInvoke((ESKAN_ADD_REMOVE_MESSAGEFILTER)MessageFilter_AddRemove_Invoked,
AddFilter, Filter);
sr.AsyncWaitHandle.WaitOne(2000);
}
}

下面是我到目前为止转换的代码,包括我正在努力处理的 BeginInvoke 部分。

    private void MessageFilter_AddRemove_Invoked(bool addFilter, System.Windows.Forms.IMessageFilter filter)
{
if (addFilter)
{
System.Windows.Forms.Application.AddMessageFilter(filter);
}
else
{
System.Windows.Forms.Application.RemoveMessageFilter(filter);
}
}

private void MessageFilter_AddRemove(bool addFilter, System.Windows.Forms.IMessageFilter filter)
{
{
IAsyncResult sr = System.Windows.Threading.Dispatcher.BeginInvoke((ESKAN_ADD_REMOVE_MESSAGEFILTER)MessageFilter_AddRemove_Invoked, addFilter, filter);
sr.AsyncWaitHandle.WaitOne(2000);
}
}

如果还有其他错误,请告诉我。

谢谢

最佳答案

那是因为Dispatcher.BeginInvoke ,虽然它可能是等效的逻辑操作,但不返回 IAsyncResult,它返回 DispatcherOperation .看看this blog post您将看到一个很好的例子,说明 Dispatcher 是如何工作的。我已将相关代码示例复制到此处以确保它稍后存在。

public Window1()
{
InitializeComponent();

CheckBox myCheckBox = new CheckBox();
myCheckBox.Content = "A Checkbox";

System.Threading.Thread thread = new System.Threading.Thread(
new System.Threading.ThreadStart(
delegate()
{
System.Windows.Threading.DispatcherOperation
dispatcherOp = myCheckBox.Dispatcher.BeginInvoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
myCheckBox.IsChecked = true;
}
));

dispatcherOp.Completed += new EventHandler(dispatcherOp_Completed);
}
));

thread.Start();
}

void dispatcherOp_Completed(object sender, EventArgs e)
{
Console.WriteLine("The checkbox has finished being updated!");
}

注意这一行:

dispatcherOp.Completed += new EventHandler(dispatcherOp_Completed);

这就是您将知道它何时完成的方式 - 它会通过该事件给您回电。

关于c# - 如何正确使用 Dispatcher.BeginInvoke?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15926310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com