I have a WCF Service (several, actually) called by a WPF application, all under .NET 4.0. Using the QuickBooks Integrator 5.0 from nsoftware (a .NET wrapper library for the QuickBooks SDK), most of my routines work fine. However, when some of them are run from a new thread, AND there's an error, particularly one where the QuickBooks file can't be opened, then I get a wide variety of strange errors, including an SEHException, both an "invalid arg status util" and a "procedure entry point not found" in QBUtilities.dll, and an access exception violation.
For example, 开发者_如何学Cthe routine when called directly from the client, works as expected. Let's say I deliberately load the wrong QuickBooks file (meaning QuickBooks cannot open the file my application is expecting; a fatal trappable error) and call it:
GetCustomerWithQB(int CustID)
{
.. set up code
..
try {
..
..
toReturn.QBCustomer.QBCustomer.Get(QuickBooksId); // this goes to QB to do the fetch
}
catch (nsoftware.InQB.InQBException x)
{
// we get, correctly, a 602 "there is a different file open" error.
}
}
However, if I call that routine from within the service, spawning a new thread:
Task.Factory.StartNew(delegate { GetCustomerWithQB(CustID); });
Then I get the variety of errors above. GRRRR. Help?
After extensive debugging and a day's worth of research, it turns out that I only got the weird errors when I had TWO routines calling at once. This led me to investigate a number of avenues, the most useful of which was this question. Bottom line, I created a static single-threaded StaTaskScheduler (from the Microsoft's Parallel Extensions library):
_staSchedulerForQBCalls = new StaTaskScheduler(numberOfThreads:1);
and used it for all the tasks calling QuickBooks:
Task.Factory.StartNew(delegate { GetCustomerWithQB(CustID); }, CancellationToken.None, TaskCreationOptions.None, _staSchedulerForQBCalls);
As these things usually do, it seems reasonably obvious in hindsight, but the bizarre errors and limited circumstances of problems certainly didn't point me in this direction at first.
精彩评论