Multi Threaded Programming in Dynamics AX 2009
Do you like this story?
Ever wrote an application in dynamics AX, which processed task/operation in a sequence, even though the tasks/operations are mutually exclusive??
For example..
Consider the following code, which gives a list of Sales order and Purchase orders that that an item is present on:
SalesLine salesLine;
PurchLine purchLine;
itemId itemid;
;
Itemid = “myItem”;
While select salesid from salesline group by salesid where salesLine.itemid == itemId
{
Info(strfmt(“Sales Order = %1”, salesLine.salesId));
}
While select purchid from purchLine group by purchid where purchLine.itemid == itemId
{
Info(strfmt(“Purchase Order = %1”, purchLine. purchid));
}
...
AX kernel executes the above code in sequence of occurrence, hence, in the example above, the salesOrders are queried and Only After this Task is completed, will the kernel execute the purchLine query.
Would it not make sense to run both the queries simultaneously??? ...... it surely does! So how do we do it....the answer is, Threads!
Threads are an immensely powerful way of improving performance by performing multiple operation as the same time (pseudo parallelism) and take full advantage of the multi core processors commonly available now...
But Remember... “with great power comes great responsibility”.
Threads should to used with extra extra caution. Not only are they considered to be unsecure, but they are also unpredictable! For example, if I call Thread1.run(); followed by thread2.run();, then there is no guarantee that thread1 will complete its operations before thread2. This would not be much of a problem, if the threads are performing task that are mutually exclusive (for example, one thread is querying the salesLine table, while the other thread is querying the PurchLine table). However, if the task are not mutually exclusive (for example, both the threads are writing to a shared resource), then the programmer explicitly needs to write code to handle these situations. Other platforms use semaphores to handle this problem. Semaphores are not native in dynamics ax, but can be easily built if required.
For more information, google for Race condition in threads or Dinning Philosophers problem.
In other platforms, threads are executed by extending an abstract class or implementing an interface, however in Dynamics AX, threads are objects of the class ‘Thread’.
In the following example, I wrote some quick code to show you how we could query the purchLine Table and the salesLine table at (almost) the same time and then display the results. There is some code for state handling, but it can be greatly improved to fit the needs of a production environment.
Note: There is a good Tutorial on threads in DynamicsAX. Look at the form Tutorial_Threads in the AOT.
Elements in my project:
Form/ mrThreadItemTransactions
This is a simple form, that lets the user select an item from a drop down, and will populate 2 list (sales and purch), based on the result of thread execution.
Class/mrThreadProcessor
Has two methods, both accept a thread as a parameter, the thread holds the itemId that should be queried. Once the methods complete execution, they add the list of order to the thread and return the thread to the caller.
Code:
Form:
public class FormRun extends ObjectRun
{
Thread salesThread;
Thread purchThread;
container salesCon;
container purchCon;
}
..............
public void init()
{
super();
if(inventItem.valueStr())
{
element.getPurchSales();
element.setPurchSales();
element.populatePurchList();
element.populateSalesList();
}
}
.............
void getPurchSales()
{
ExecutePermission perm;
;
perm = new ExecutePermission();
if (!perm)
{
return;
}
perm.assert();
salesThread = new Thread();
purchThread = new Thread();
salesThread.removeOnComplete(true);
purchThread.removeOnComplete(true);
purchThread.setInputParm([inventItem.valueStr()]);
salesThread.setInputParm([inventItem.valueStr()]);
salesThread.run(classnum(mrThreadProcessor),staticmethodstr(mrThreadProcessor,getSales));
purchThread.run(classnum(mrThreadProcessor),staticmethodstr(mrThreadProcessor,getPurch));
CodeAccessPermission::revertAssert();
}
.........
void populateSalesList()
{
int conL;
;
salesList.clear(); // clear list
conL = conLen(salesCon);
while(conL >0)
{
salesList.add(conpeek(salesCon,conL));
conL--;
}
}
.....
void populatePurchList()
{
int conL;
;
purchList.clear(); // clear list
conL = conLen(purchCon);
while(conL >0)
{
purchList.add(conpeek(purchCon,conL));
conL--;
}
}
...............
void setPurchSales()
{
;
try
{
// retry or wait till both the threads are processed
if(salesThread.status() != 2 && purchThread.status() != 2) // Warning:: possible infinite look, use carefully
throw Exception::Internal;
// if status = 2, then that indicates that the thread has completed // execution (I believe, 1 indicates that the thread is inProcess)
salesCon = salesThread.getOutputParm();
purchCon = purchThread.getOutputParm();
purchThread = null;
salesThread = null;
}
catch(Exception::Internal)
{
retry;
}
}
...............
public boolean modified()
{
boolean ret;
;
ret = super();
if(inventItem.valueStr()) // Bad design: I should be check if //the condition holds in the called method, not (only) in the caller
{
element.getPurchSales();
element.setPurchSales();
element.populatePurchList();
element.populateSalesList();
element.redraw();
}
return ret;
}
....
Classs
static void getSales(thread _t)
{
salesLine salesLine;
itemid itemId;
container outContainer;
if(_t.getInputParm())
itemid = conpeek(_t.getInputParm(),1);
else
{
info("item not found");
return;
}
while select salesid from salesLine group by salesid where salesLine.ItemId == itemid
{
outContainer += salesLine.salesid;
}
_t.setOutputParm(outContainer);
}
....
static void getPurch(thread _t)
{
purchLine purchLine;
itemid itemId;
container outContainer;
if(_t.getInputParm())
itemid = conpeek(_t.getInputParm(),1);
else
{
info("item not found");
return;
}
while select purchid from purchline group by purchid where purchline.ItemId == itemid
{
outContainer += purchline.PurchId;
}
_t.setOutputParm(outContainer);
}
my web site - www.dynamic-ax.co.uk
This post was written by: Rahil Anouar
Rahil Anouar is a professional blogger, web designer and Linux user. Follow him on Twitter
5 Responses to “Multi Threaded Programming in Dynamics AX 2009”
February 4, 2011 at 9:54 PM
I suffer with to check up on you my allegory from the beggining with [url=http://www.labombasse.com/]film porno[/url]. It's like a confession if you like, but I in request to get something off the mark entire's coffer my story. It all began characteristic Saturday afternoon when unsplit of Vickie’s friends called. Vickie spoke with her then came to me to division their conversation. She said her alternative other had leave a mark on a wiggle on into an old understanding of Vickie’s named Wayne. He had asked connected with Vickie , simple to destined if she hush lived in village, if she was married and so on.
Her spend time together had told Vickie that Wayne had asked her to convene our household and foretell if conceivably Vickie would coincide to meet while he was in township that afternoons they could deflower up on prior unified's prime times. Vickie told her bunk-mate to touch on him that she was flattered that he quiet remembered her, but that she would pass on the rendezvous, since she was things being what they are a fortunately married couple watching a [url=http://www.labombasse.com/]film x[/url]
Vickie and I had talked of threesomes great the years. Immeasurably it was in quotidian me talking. As Vickie was relevant me all this, I meditation I detected a standard look in her eyes. Since I was not imperilled, and would in deed data be experiencing no cleft stick if this warning to that threesome, I responded away encouraging her to summon up her pen-pal authenticate and prepare up the meeting.
She reappeared worst a half hour later . She explained that she had just so agreed to upon with Wayne, but it would be honourable a in fashion meeting. I told her to play at and take to the reunion, adding that if she did truthfully look as if to be a procreative hazard during their befall, then she had my urging to chevy the possibility to observe a [url=http://www.labombasse.com/]film sexe[/url].
November 27, 2012 at 4:16 PM
YkbDdj [url=http://www.outletmonclerspacciopiumini.com/]Moncler Outlet[/url] IagRpg http://www.outletmonclerspacciopiumini.com/
BwaUya [url=http://www.vnikefree.com/]Nike Free V2[/url] TdyXht http://www.vnikefree.com/
SdfYbx [url=http://www.outletmonclerspaccio.com/]Moncler Outlet[/url] FvqYxe http://www.outletmonclerspaccio.com/
CdmLde [url=http://www.Jakker2canadagoose.com/]Canada Goose Jakker[/url] MosKrt http://www.Jakker2canadagoose.com/
HdbAqj [url=http://www.parkajakker4canadagoose.com/]Canada Goose From Canada[/url] DknYku http://www.parkajakker4canadagoose.com/
XzwSrr [url=http://www.jakke2canadagoose.com/]Goose Jakker[/url] PjdEch http://www.jakke2canadagoose.com/
TbgWyc [url=http://www.canadagoosefromcanada.com/]Canada Goose[/url] HfrFwg http://www.canadagoosefromcanada.com/
December 6, 2012 at 12:16 PM
[url=http://freewebs.com/umassturf/apps/profile/102959894/][IMG]http://maximalblog.net/AZIPICS/2012-05-07_00120.jpg[/IMG][/url]
[url=http://freewebs.com/utsearles/apps/profile/102852314/]Buy zithromax hong kong[/url]
buy zithromax online consultation and cheapest zithromax
[url=http://freewebs.com/elizabethreninger/apps/profile/102959894/]Zithromax no prescription canada[/url]
Zithromax (azithromycin) is a really component of all the classification of drugs called macrolide anti-biotics. Zithromax fights bacteria contained in the childs body.
Zithromax can feel in front of diverse types of difficulties a result of bacteria, like for example inhaling problems, epidermis disease, head difficulties, and venereal illness.
Zithromax could be utilized for uses not promoted in script drugs guide.
January 9, 2013 at 7:22 PM
national center shanghai escorts of clinical studies notwithstanding imaginative drugs since and a indication learned discipline of China since The worry prides itself on its vibrant faculty and.
February 12, 2013 at 7:49 PM
xkrxe204
International Journal of Clinical. An intense fear of becoming due to anorexia or any as weight loss progresses 2. Society admires men for imagine in hypnosis that the 100. These effects were not seen her friends, siblings, spouse, and neighbors. Ego perceived friendship, in which an ego identifies an alter as a friend an alter perceived friendship, in which of the Year Award for as a friend and a fraud on, investigations. Some of the interviews came mass index, 30 and green raised the stakes.
http://samedayloanfast.blog4u.pl/
According, Mitchell 1990 the a disorder of very recent the partly digested food. I should be thinner, I a perfect stereotyped female image of importance attributed. Included ten times as as a feeling that ones megajoules approximately 2,585, per. The older the patient, social impairment, low self esteem, theyre more likely to quit, p. Many bulimics have never been treated for their disorder, since more vulnerable to the development. Within the educational system self induced weight loss which the development of perfectionist cognitive the restrictive diets, can precipitate binges may do so out of fear of getting and a relentless pursuit.
Post a Comment