Главная страница
    Top.Mail.Ru    Яндекс.Метрика
Форум: "Основная";
Текущий архив: 2003.08.07;
Скачать: [xml.tar.bz2];

Вниз

Как правильно прекратить поток?   Найти похожие ветки 

 
mmss   (2003-07-24 14:25) [0]

Пауза - TestTh.Suspend; Продолжение - TestTh.Resume; А вот по Terminate или Free прога виснет, или не откликается...
Заранее спасибо.


 
Caligula   (2003-07-24 14:34) [1]

Во время создания потока желательно прописать такую штучку:

Thread.FreeOnTerminate := True;

А потом сделать непосредственно Terminate. Делать процедуру Free вообще тогда не будет нужно (делается автоматически). У меня работало, посмотрим, что будет у тебя. Желательно приоритет поставить на tpNormal.


 
mmss   (2003-07-24 14:40) [2]

procedure TForm1.Button2Click(Sender: TObject);
begin
TestTh := TGoThread.Create (False); // start
TestTh.FreeOnTerminate := True;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
TestTh.Terminate;
end;


Вот старт и стоп, на стоп нажимаю, вообще ни какой реакции, пауза и возобновить работают нормально.


 
mrcat   (2003-07-24 14:44) [3]

где Execute ?


 
Skier   (2003-07-24 14:48) [4]

>mrcat © (24.07.03 14:44)
If CreateSuspended is False, Execute is called immediately


 
mrcat   (2003-07-24 14:54) [5]

Skier © (24.07.03 14:48)

имею ввиду: где код процедуры Execute ?


 
Skier   (2003-07-24 15:04) [6]

>mrcat © (24.07.03 14:54)
ПонЯл.


> где код процедуры Execute ?


Ждём-с...:)


 
Reindeer Moss Eater   (2003-07-24 15:10) [7]

procedure TForm1.Button1Click(Sender: TObject);
begin
TestTh.Terminate;
end;
Вот старт и стоп, на стоп нажимаю, вообще ни какой реакции, пауза и возобновить работают нормально.


TestTh.Terminate не убивает поток. Этот метод лишь выставляет Terminated-флаг у потока. Если поток не обращает на это внимания, то ничего и не должно произойти.


 
mmss   (2003-07-24 15:13) [8]

Такой код:

...
private
FItemsProcessed: Integer;
...

procedure TGoThread.Execute;
begin
for i:=0 to 100000 do
begin
Memo1.Lines.Add(IntToStr(i));
if I Mod 20 = 0 then
FItemsProcessed := i;
Synchronize(SetStatusLine);
end;
end;
end;

procedure TGoThread.SetStatusLine;
begin
Form1.Gauge1.Progress:=Round(100*FItemsProcessed/100000-1);
end;


 
Reindeer Moss Eater   (2003-07-24 15:14) [9]

Как и ожидалось, твоему потоку по барабану, что там ему снаружи говорят.


 
mmss   (2003-07-24 15:18) [10]

Т.е. Reindeer Moss Eater (24.07.03 15:14)
как сделать, чтобы не по барабану было???


 
Reindeer Moss Eater   (2003-07-24 15:19) [11]

Проверять, не выставлен ли флаг Terminated и выходить из Execute


 
Verg   (2003-07-24 15:24) [12]

Такой поток можно завершить только
TerminateThread

.....
Remarks

TerminateThread is used to cause a thread to exit. When this occurs, the target thread has no chance to execute any user-mode code and its initial stack is not deallocated. DLLs attached to the thread are not notified that the thread is terminating.
TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:

· If the target thread owns a critical section, the critical section will not be released.
· If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread"s process could be inconsistent.
· If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.



A thread cannot protect itself against TerminateThread, other than by controlling access to its handles. The thread handle returned by the CreateThread and CreateProcess functions has THREAD_TERMINATE access, so any caller holding one of these handles can terminate your thread.
If the target thread is the last thread of a process when this function is called, the thread"s process is also terminated.
The state of the thread object becomes signaled, releasing any other threads that had been waiting for the thread to terminate. The thread"s termination status changes from STILL_ACTIVE to the value of the dwExitCode parameter.

Terminating a thread does not necessarily remove the thread object from the system. A thread object is deleted when the last thread handle is closed.


 
mrcat   (2003-07-24 15:24) [13]

mmss (24.07.03 15:13)

удивительно что код сам по себе работает, т.к. обращаетесь к VCL во вторичном потоке, что запрещено ;)


 
mmss   (2003-07-24 15:25) [14]

Добавил в Execute
if terminated then exit;
И стало работать!!!
Спасибо всем за неоценимую помощь!!!



Страницы: 1 вся ветка

Форум: "Основная";
Текущий архив: 2003.08.07;
Скачать: [xml.tar.bz2];

Наверх





Память: 0.47 MB
Время: 0.009 c
3-20399
Zelius
2003-07-14 20:04
2003.08.07
Асинхронность в ADO


3-20440
DBDev
2003-07-17 12:13
2003.08.07
Кто-нибудь создавал ODBC алиасы программно?


3-20454
Nikolai_S
2003-07-17 15:40
2003.08.07
Проблема с Lookup полями в ADO с MS SQL Server


1-20535
Evg12
2003-07-26 16:00
2003.08.07
Форма с автосайзом


14-20808
K$oft
2003-07-22 16:51
2003.08.07
Хелп для Delphi





Afrikaans Albanian Arabic Armenian Azerbaijani Basque Belarusian Bulgarian Catalan Chinese (Simplified) Chinese (Traditional) Croatian Czech Danish Dutch English Estonian Filipino Finnish French
Galician Georgian German Greek Haitian Creole Hebrew Hindi Hungarian Icelandic Indonesian Irish Italian Japanese Korean Latvian Lithuanian Macedonian Malay Maltese Norwegian
Persian Polish Portuguese Romanian Russian Serbian Slovak Slovenian Spanish Swahili Swedish Thai Turkish Ukrainian Urdu Vietnamese Welsh Yiddish Bengali Bosnian
Cebuano Esperanto Gujarati Hausa Hmong Igbo Javanese Kannada Khmer Lao Latin Maori Marathi Mongolian Nepali Punjabi Somali Tamil Telugu Yoruba
Zulu
Английский Французский Немецкий Итальянский Португальский Русский Испанский