各位,我是新手,请教多线程问题,万分感激(100分)

  • 主题发起人 主题发起人 极乐使者
  • 开始时间 开始时间

极乐使者

Unregistered / Unconfirmed
GUEST, unregistred user!
我用多线程更新数据库,程序如下:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, Grids, DBGrids, DB, ADODB;
type
TForm1 = class(TForm)
ADOTable1: TADOTable;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
BitBtn1: TBitBtn;
ADOTable2: TADOQuery;
procedure BitBtn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
implementation
{$R *.dfm}
function MyThreadFunc(P:pointer):Longint;stdcall;
var
i:integer;
begin
form1.ADOTable2.First;
for i:=1 to 5do
begin
form1.ADOTable2.Edit;
form1.ADOTable2.FieldByName('现价').AsFloat:=6.28;
if not(form1.ADOTable2.Eof) then

form1.ADOTable2.next;
end;

end;
procedure TForm1.BitBtn1Click(Sender: TObject);
var
hThread:Thandle;
ThreadID:DWord;
begin

hthread:=begin
Thread(nil,0,@MyThreadfunc,nil,0,ThreadID);
if hThread=0 then
messagebox(Handle,'Didn’t Create a Thread',nil,MB_OK);
end;
end.

运行至线程函数最末时总出错,提示'access violation at XXXXXX,write of address XXXXX',请各位高手赐教,谢谢.'
 
用DELPHI,你就继承TThread写代码嘛!
 
没错,建议从TThread继承写自己的线程类。
另外用你的代码的话,建议在:
form1.ADOTable2.FieldByName('现价').AsFloat:=6.28;
后面加一句试试:
form1.ADOTable2.post;
 
我以前曾同样碰到这样的问题。delphi中的begin
thread函数已转为pascal的调用协定
不需要在这函数中改为stdcall。将stdcall去掉即可。
function MyThreadFunc(P:pointer):Longint;//stdcall;
var
i:integer;
begin
form1.ADOTable2.First;
for i:=1 to 5do
begin
form1.ADOTable2.Edit;
form1.ADOTable2.FieldByName('现价').AsFloat:=6.28;
if not(form1.ADOTable2.Eof) then

form1.ADOTable2.next;
end;
end;
//创建线程时去掉线程函数的@
hthread:=begin
Thread(nil,0,MyThreadfunc,nil,0,ThreadID);
不妨试试
OK
 
不行啊.这回出现键列信息不足或不正确,更新影响到多行.
 
不好意思,上次有个地方写错了。
hthread:=begin
Thread(nil,0,MyThreadfunc,self,0,ThreadID);//将要传递的参数由nil改为self即可。再试
 
Destroy時要EndThread
 
老兄,还是出现上面的信息,如果你有程序,帮忙发给我看看.谢谢.
freempire@163.com
 
//看一下
var
Form1: TForm1;
hThread:Thandle;
implementation
{$R *.DFM}

function WaitFor : DWORD;
var
Msg: TMsg;
H: THandle;
begin
H := hThread;
if GetCurrentThreadID = MainThreadID then
while MsgWaitForMultipleObjects(1, H, False, INFINITE,
QS_SENDMESSAGE) = WAIT_OBJECT_0 + 1do
PeekMessage(Msg, 0, 0, 0, PM_NOREMOVE)
else
WaitForSingleObject(H, INFINITE);
GetExitCodeThread(H, Result);
end;

function MyThreadFunc(P:pointer):Longint;stdcall;
var
i:integer;
begin
form1.ADOTable2.First;
for i:=1 to 5do
begin
form1.ADOTable2.Edit;
form1.ADOTable2.FieldByName('?ɲ').AsFloat:=6.28;
if not(form1.ADOTable2.Eof) then
form1.ADOTable2.next;
end;
result := 0;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
ThreadID:DWord;
begin
hthread:=begin
Thread(nil,0,@MyThreadfunc,nil,0,ThreadID);
if hThread=0 then
messagebox(Handle,'Didn¡¦t Create a Thread',nil,MB_OK);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
WaitFor;
EndThread(hThread);
end;
 
不行啊.还是出现键列信息不足或不正确,更新影响到多行.
 

Similar threads

后退
顶部