我在某些机器上遇到应用程序崩溃问题,在事件查看器中我可以看到跟随错误。
由于uhhandled异常,AggregateException
,该进程终止我正在执行以下操作
启动任务以连续轮询IE窗口。此代码使用窗口类和标题(使用本机win32 api)查找窗口对象。
public static CancellationTokenSource HandlePopup(
this HostedControlBase control, string className, string caption,
int? milliSecondsWaitBeforeAction, Action<IntPtr> onSuccessCallBackAction)
{
var cancellation = new CancellationTokenSource();
IntPtr outputWindowPtr = IntPtr.Zero;
var controlLocal = control; //// for thread safety.
try
{
var t = Task.Factory.StartNew(
() => Thread.Sleep(milliSecondsWaitBeforeAction ?? 0),
cancellation.Token,
TaskCreationOptions.None,
TaskScheduler.Default).ContinueWith(
(prevTask) =>
{
var condition =
new AndCondition(
new PropertyCondition(AutomationElement.ClassNameProperty, className),
new PropertyCondition(AutomationElement.NameProperty, caption));
AutomationElementCollection collection = null;
if (cancellation.IsCancellationRequested)
{
cancellation.Token.ThrowIfCancellationRequested();
return;
}
do
{
if (cancellation.IsCancellationRequested)
{
cancellation.Token.ThrowIfCancellationRequested();
return;
}
try
{
collection = AutomationElement.RootElement.FindAll(TreeScope.Children, condition);
if (collection.Count <= 0)
{
continue;
}
outputWindowPtr =
new IntPtr(
collection[0].Current.NativeWindowHandle);
break;
}
catch (ElementNotAvailableException)
{
}
}
while (true);
},
cancellation.Token,
TaskContinuationOptions.NotOnFaulted,
TaskScheduler.Default).ContinueWith(
(prevTask) =>
{
if (!prevTask.IsFaulted)
{
////if (outputWindowPtr.Equals(IntPtr.Zero))
////{
//// return;
////}
if (controlLocal.InvokeRequired)
{
controlLocal.Invoke(onSuccessCallBackAction, outputWindowPtr);
}
else
{
onSuccessCallBackAction(outputWindowPtr);
}
}
},
cancellation.Token,
TaskContinuationOptions.NotOnFaulted,
TaskScheduler.Default);
////t.Wait(cancellation.Token);
return cancellation;
}
catch (AggregateException ex)
{
ex.Handle(exnew => true);
return null;
}
}
HostedControlBase是Winforms用户控件,此代码首先会休眠几秒钟(如果指定),然后继续使用它的标题和窗口类名称搜索窗口。如果找到该窗口,它会调用一个回调函数,该函数使用该方法返回的“CancellationTokenSource”取消该任务。
最大的问题
这是我正在做的事情的正确方法吗?你是专家在这里看到任何缺陷,我的应用程序在某些特定的机器上被终止。