Most instance members of the objects in the ADAM API are not thread-safe.
This has been done especially to reduce the complexity of the code and thus
improve the performance and reliability. However that does not mean that
the ADAM API can not be used in a multi-threaded application.
The first thing to note is that the Application-object isn't thread
safe either. This is especially important in a Web environment, because this means that
you shouldn't use a singleton or an instance returned by a static property in
ASP.NET. This will give unpredicable results. You should make sure that
every HTTP request has its own Application. If you use the ADAM web
framework as well, then this is all done for you.
If you want to create multiple threads and have them all use the same ADAM session,
then you should prepare an Application instance in your main thread and
call Application.Clone() to create one clone of this
Application instance for each thread that you want to use. Then give each thread its own
cloned Application instance. Then work like you normally would within the thread. This ensures that
all threads share the same session in ADAM, without having to log on multiple times
and without having to worry about concurrency conflicts.
Note: you should never share instance of other data objects (e.g. Record or Classification)
between threads either. This is not supported and will most likely fail.
| C# |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
[STAThread]
static void Main(string[] args)
{
Application app = new Application();
try
{
// Logging on...
app.LogOn(myRegistration, myUserName, myPassword);
// Creating one thread to do something...
Thread thread1 = new Thread(new ParameterizedThreadStart(RunThread));
thread1.Start(app.Clone());
// Creating another thread to do something...
Thread thread2 = new Thread(new ParameterizedThreadStart(RunThread));
thread2.Start(app.Clone());
// Loading some records in the main thread
RecordCollection records = new RecordCollection(app);
records.Load(new SearchExpression("hello"));
Console.WriteLine(records.Count);
// Waiting for all these threads to complete...
thread1.Join();
thread2.Join();
}
finally
{
app.Logoff();
}
}
private static void RunThread(object data)
{
Application app = (Application)data;
// Loading some records in this thread
RecordCollection records = new RecordCollection(app);
records.Load(new SearchExpression("hello"));
Console.WriteLine(records.Count);
}
|