Delphi Firemonkey在主线程 异步调用函数(延迟调用)
先看下面的FMX.Layouts.pas中一段代码
procedure TCustomScrollBox.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Single); begin FMouseEvents := True; inherited; if (Button = TMouseButton.mbLeft) then begin MousePosToAni(X, Y); AniMouseDown(ssTouch in Shift, X, Y); end; end;
在执行Inherited;这行时可能会调用控件的OnDblClick事件,如果此时在OnDblClick中将Form或控件释放了,后面调用MousePosToAni可能就会造成内存访问异常
因此最好能够在UI线程(主线程)中执行MouseDown完全后,再调用Form或控件的释放,如下面
procedure TForm1.OnListBox1Item1DblClick(Sender:TObject); begin ....//处理一些事情 AsyncCallInUIThread( procedure begin Self.DisposeOf; //延迟释放,防止内存访问异常 end); end;
下面是AsyncCallInUIThread的实现:
procedure AsyncCallInUIThread(Proc: TProc); begin TThread.CreateAnonymousThread( procedure begin Sleep(0); TThread.Synchronize(nil, procedure begin Proc; end); end).Start; end;