首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

子线程更新主窗体进度条,拖动主窗体卡死,求解决,该如何解决

2012-12-30 
子线程更新主窗体进度条,拖动主窗体卡死,求解决创建了一个子线程,传了一个进度值 totalsent 更新主窗体进

子线程更新主窗体进度条,拖动主窗体卡死,求解决
创建了一个子线程,传了一个进度值 totalsent 更新主窗体进度条(FOnProgress),不拖动主窗体这个没问题,但是2、3秒拖动一次主窗体就会停滞卡死,求解决办法,子线程代码如下:
EnterCriticalSection(critical1);
  try
       totalsent:=totalsent+BytesSent;
    if     Assigned(FOnProgress) then
   Synchronize(   Progress) ;
   LeaveCriticalSection(critical1);
 except
   on e:Exception do
   begin
    LeaveCriticalSection(critical1);
    ShowMessage(e.message);
   end;
 end;

[解决办法]

Sleep(100);
   Application.ProcessMessage;



EnterCriticalSection(critical1);
  try
    totalsent:=totalsent+BytesSent;
    if Assigned(FOnProgress) then
   Synchronize(Progress) ;
   Sleep(100);
   Application.ProcessMessage;
   LeaveCriticalSection(critical1);
 except
   on e:Exception do
   begin
    LeaveCriticalSection(critical1);
    ShowMessage(e.message);
   end;
 end;

[解决办法]
线程中最好不要直接去操作窗体,使用消息来进行通知。
postmessage(formHandle,自己的消息,)
窗体收到消息后在进行操作。
[解决办法]
[code=delphi]
  EnterCriticalSection(critical1);
  try
    totalsent:=totalsent+BytesSent;
  finally
    LeaveCriticalSection(critical1);
  end;
  try
    if Assigned(FOnProgress) then
      Synchronize(Progress);
    Sleep(100);
    Application.ProcessMessages;
  except
   on e:Exception do
    //ShowMessage(e.message);
  end;
[code]
[解决办法]
什么原因,不清楚。但代码还是有点问题,
 if     Assigned(FOnProgress) then
   Synchronize(   Progress) ;
上面这段在EnterCriticalSection(critical1) 与 LeaveCriticalSection(critical1)之间,感觉很别扭,因为Synchronize也是同步。另外try..except不如换成try..finally。
而且加临界区是为了同步 totalsent吗?如果对于 totalsent只是子线程写,主线程读,那就不需要临界区。所以直接这样试试:
       totalsent:=totalsent+BytesSent;
    if     Assigned(FOnProgress) then
   Synchronize(   Progress) ;

引用:
亲,那个showmessage,是调试时加上去的,用 postmessage是能解决窗体拖动时 卡死的情况,但是是什么原因导致卡死的?ZyxIp还能解释下?

引用:
[code=delphi]
  EnterCriticalSection(critical1);
  try
    totalsent:=totalsent+BytesSent;
……

[解决办法]
临界区的用法是有点怪。不过这段代码似乎没有什么问题,会不会是你线程中其它代码对主线程窗体进行操作?
或者在Synchronize(   Progress) ;过程中也用到了临界区,导致死锁

热点排行