:CoInitializeを/に、counitialize
以下は、プロジェクトに含める例のユニットです。そしてあなたのHTTPサーバーコンストラクタでは、カスタムスケジューラを作成するだけで、Indyはデフォルトの代わりにこれを使用します。
これを行うと、各クライアントスレッドはCOM用に適切に初期化され、すべてのクライアントスレッドで共有される他のアイテムを追加することもできます。
また、接続ごとにカスタムのTIdServerContext子孫を作成します(HTTPサーバーコンストラクタでもContextClassプロパティを設定します)。異なる種類のサーバーには異なるTIdServerContext子孫がありますが、すべてTsoIndyCOMEnabledSchedulerOfThreadベーススレッドクラスをすべて使用します何らかのCOMをする。
スレッドにADO接続を挿入するのではなく、コンテキストに挿入します。特にこれをスレッドプールに追加する場合は特にです。
unit ExampleStackOverflow;
interface
uses
SysUtils, Classes,
ActiveX,
IdThread, IdSchedulerOfThreadDefault;
type
//Meant to be used with a custom TIdSchedulerOfThreadDefault descendant
//to ensure COM support on child threads.
TsoIndyComThreadWithTask = class(TIdThreadWithTask)
protected
//Ensure COM is setup before client connection/thread work
procedure BeforeExecute; override;
//Graceful COM cleanup on client connection/thread
procedure AfterExecute; override;
end;
TsoIndyCOMEnabledSchedulerOfThread = class(TIdSchedulerOfThreadDefault)
public
constructor Create(AOwner:TComponent); reintroduce;
end;
implementation
procedure TsoIndyComThreadWithTask.BeforeExecute;
begin
CoInitialize(nil);
inherited;
end;
procedure TsoIndyComThreadWithTask.AfterExecute;
begin
inherited;
CoUninitialize();
end;
constructor TsoIndyCOMEnabledSchedulerOfThread.Create(AOwner:TComponent);
begin
inherited;
//the whole reason for overriding default scheduler of thread is to setup COM
//on client threads
ThreadClass := TsoIndyComThreadWithTask;
Name := Name + 'COMEnabledScheduler';
end;
本当に簡単ですね。ですからTAdoConnectionオブジェクトとブール値「アクティブ」を持つクラスTMyConnectionObjectを作成してください。そして私はGLOBAL TStringListまたはTListを持っています。 OnCommandGetが起動されると、私はすべてのオブジェクトをループして、「非アクティブ」を探します。もし私がそれを使用していれば;それ以外の場合は作成して追加します。 OnCommandGetが正確に同じタイミングで起動され、処理が同じオブジェクトを取得する可能性はありますか? –
スレッドの安全性を念頭に置くには、クリティカルセクションを使用するだけですか? –
あなたはポイントを持っています。私の更新を読む:2つの接続スレッドが同時にリストにアクセスしようとする可能性があります。スレッドセーフなリスト(http://docwiki.embarcadero.com/CodeExamples/en/TThreadList_(Delphi))、CriticalSectionなど、スレッド固有の戦略を使用する必要があります。http:// www。 eonclash.com/Tutorials/Multithreading/MartinHarvey1.1/ToC.html –