VCL是非线程的,使用VCL相关的东东一定要使用 Synchronize.
具体可以看delphi 的 Help Using the main VCL thread
具体可以看delphi 的 Help Using the main VCL thread
解决方案 »
- 谁有idhttp用http协议上传下载例子啊 另外服务器需要设置啥?
- delphi的变量取值范围是多少
- 分解一个字符串,头疼了,怎么都不对
- 复合sql句子里怎么用sort来排序?查询
- 请教delphi 2005 如何安装以前delphi7的控件?
- 关于Calculated的问题,很是郁闷!!!
- Exception EDBEngineError in module ***.exe
- 一个概念性问题?
- 斑竹:自己的贴子怎么样才能删除?我提的问题有好多都自己解决了
- VC中有CDragListBox,对应的delphi中是哪个控件或怎样设置?
- Delphi 是不是也要.net了,那VCL怎么办?
- 怎样动态创建控件和设置属性?
Don't call WaitFor in the context of the main VCL thread if the thread uses Synchronize. Doing so will either cause a deadlock, making it appear that the application has hung, or raise an EThread exception.Synchronize waits for the main VCL thread to enter the message loop before allowing the method it is trying to synchronize to execute. If the main VCL thread has called WaitFor, it won't enter the message loop and Synchronize will never return. TThread detects that case and will raise an EThread exception in the thread causing it to terminate and, if not caught in the Execute method, the application will terminate as well. If Synchronize is already waiting on the main VCL thread when WaitFor is called, TThread can't intervene, and the application will deadlock.
所有,如果线程中使用了 vcl,Synchronize一定不要使用waitfor.保证主程序退出时线程一定已关闭,可能要根据具体情况.
把Thread的FreeOnTerimte := Ture;
FormClose 中Thread.Free; 等
可以贴一些代码吗?
问题。不用Synchronize,照样可以操纵VCL。
TThreadProc = procedure of object;TMyThread = class(TThread)
private
FThreadProc: TThraedProc;
protected
procedure Execute; override;
public
constructor Create(ActionProc: TThreadProc; TerminateProc: TNotifyEvent);
end;...
implementationprocedure TMyThread.Execute;
begin
FThreadProc;
end;constructor TMyThread.Create(ActionProc: TThreadProc; TerminateProc: TNotifyEvent);
begin
FreeOnTerminate := True;
FThreadProc := ActionProc;
OnTerminate := TerminateProc;
inherited Create(False);
end;线程代码在ActionProc中,线程结束代码在TerminateProc中,两个代码均在
主线程环境下运行。主线程终止时必须等待从线程终止。
当然可以操作,但是不对,
例如:两个Thread同时对TStringList操作,一个修改的同时,如果不同步,
另一个同时把他的给删除了,怎么办?
>>>>因为所有的thread terminate都只是给thread发信号, 而不能保证thread是否结束
看看源码就知道,thread.termnate只是把一个变量设成True;
>>
可以看看delphi中的用Thread排序的例子,不过有问题。
可以看我提的问题有关TThread的FreeOnTerminte
http://www.midatech.com/csdn/expert/TopicView.asp?id=5
因为可以用临界区(TCriticalSection)同样能达到
Synchronize的目的
当然,同步可以使用很多方法,临界区,信号量,互斥量,事件等.Synchronize指的
是同步,还是一个函数?
Terminate只是改变一个变量的值,并不是让Thread结束.
可以看看delphi中的用Thread排序的例子,在排序过程中退出程序,没有引起一个异常,
排序时在画布上画线,和你的程序很相似.
但是在排序过程中退出程序,有内存泄漏,此问题已经讨论过.
可以看我提的问题有关TThread的FreeOnTerminte
http://www.midatech.com/csdn/expert/TopicView.asp?id=5;
程同步的问题,其实很简单:加一个控制变量,正常情况下,这个变量的值
是False,终止线程前将其设为True(由主线程完成),在线程中的每一个循环
中都监视这个变量,一旦变为True,马上Exit,线程自然终止了。在线程的
OnTerminate过程中加入一控制变量,线程开始时设为False,终止后设为True
(因为线程的实例可能已被释放,不能访问Terminated属性),只有这个变量
为True时才可以关闭窗口。
while not Terminated do
begin
刷新程序
end;
在Execute运行完以后线程就结束了,当然我认为还是应当用Synchronize,原因很简单,就是因为它简单,不用再另外弄其它东东。在你的主程序中还可以这样写:退出之前:
while not myThread.Suspended/或者别的信号 do
Application.ProcessMessages;