Go Back   NinjaTrader Support Forum > NinjaTrader 8 > Add-On Development

Add-On Development General NinjaScript development questions.

NinjaTrader
Reply
 
Thread Tools Display Modes
Old 06-18-2017, 02:10 AM   #1
GoSPvC
Junior Member
 
Join Date: Mar 2010
Location: München
Posts: 20
Thanks: 10
Thanked 5 times in 4 posts
Default Problems on throwing exceptions inside InvokeAsync()

Hi,

i have done some testing on catching the exceptions at the AddOnFramework-sample and i wondered that sometimes the code gets them and sometimes not. I found out that's because of the Dispatcher.InvokeAsync():

At mehods of the following structure:
PHP Code:
private void OnSomething(object senderEventArgs eArgs)
{
    try
    {
        
Dispatcher.InvokeAsync(() =>
        {
            throw new 
Exception("Test-Exception");
            
// Do Something
        
}
    }
    catch (
Exception exception)
    {
        
Dispatcher.InvokeAsync(() =>
        {
            
Output.Process(exception.ToString(), PrintTo.OutputTab1);
        }
    }

it seens that the exception is handled, but at another thread and thus it will NOT be printed out whereas this code:
PHP Code:
private void OnSomething(object senderEventArgs eArgs)
{
    
Dispatcher.InvokeAsync(() =>
    {
        try
        {
            throw new 
Exception("Test-Exception");
            
// Do Something
        
}
        catch (
Exception exception)
        {
            
Output.Process(exception.ToString(), PrintTo.OutputTab1);
        }
    });

handles the exception at the same thread and it is printed out correctly.
I dont know if that method (InvokeAsync() BEFORE try-catch) is a correct way to handle this problem.

Please give me some thoughts about that...

Thanks, GoS
GoSPvC is offline  
Reply With Quote
Old 06-18-2017, 02:31 PM   #2
GoSPvC
Junior Member
 
Join Date: Mar 2010
Location: München
Posts: 20
Thanks: 10
Thanked 5 times in 4 posts
Default

... after some more inquiry on that, i now understand the using of InvokeAsync(): You have to use it to update the UI instantly.

So i think the solution above is not the correct way.

I now changed my whole code the following:

1. Inside all the InvokeAsync() blocks there is only code for outputing or related to the UI.

2. Because i don't handle any exceptions anyway and i only want to display them on the Log, I now catch them global by the event handler FirstChanceException and send them all to the Log. Even exceptions inside a InvokeAsync() block could be catched (but not handled) this way.

I think my problem is solved...

Thanks, GoS
GoSPvC is offline  
Reply With Quote
Old 06-18-2017, 04:17 PM   #3
NinjaTrader_ChelseaB
NinjaTrader Customer Service
 
NinjaTrader_ChelseaB's Avatar
 
Join Date: Dec 2012
Location: Denver, CO
Posts: 7,239
Thanks: 116
Thanked 1,574 times in 1,487 posts
Default

Hello GoSPvC,

Which dispatcher are you invoking into?

Is this a random dispatcher for a new thread?

Is this the Control Center dispatcher?

Triggering the exception within a new thread means the try isn't going to wait. You would need to wait for the operation to complete.
https://stackoverflow.com/questions/...fferent-thread

Where as adding the try within the new thread as well means it will wait.
NinjaTrader_ChelseaB is offline  
Reply With Quote
The following user says thank you to NinjaTrader_ChelseaB for this post:
Old 06-19-2017, 06:22 AM   #4
GoSPvC
Junior Member
 
Join Date: Mar 2010
Location: München
Posts: 20
Thanks: 10
Thanked 5 times in 4 posts
Default

Hello Chelsea,

It is the Dispatcher used at the AddOnSample to open the window, i have not done any changes here:
PHP Code:
// Open the AddOn's window when the menu item is clicked on.
private void OnMenuItemClick(object senderRoutedEventArgs eArgs)
{
    
Globals.RandomDispatcher.BeginInvoke(new Action(() => new TradingSystemWindow().Show()));

Quote:
Where as adding the try within the new thread as well means it will wait.
This means, that way is a practicable way to solve the problem ??

Also the code above ".Wait()" added is working correct.
PHP Code:
private void OnSomething(object senderEventArgs eArgs

    try 
    { 
        
Dispatcher.InvokeAsync(() => 
        { 
            throw new 
Exception("Test-Exception"); 
            
// Do Something 
        
}).Wait();
    } 
    catch (
Exception exception
    { 
        
Dispatcher.InvokeAsync(() => 
        { 
            
Output.Process(exception.ToString(), PrintTo.OutputTab1); 
        });
    } 

Thank you, GoS
GoSPvC is offline  
Reply With Quote
Old 06-19-2017, 07:28 AM   #5
NinjaTrader_ChelseaB
NinjaTrader Customer Service
 
NinjaTrader_ChelseaB's Avatar
 
Join Date: Dec 2012
Location: Denver, CO
Posts: 7,239
Thanks: 116
Thanked 1,574 times in 1,487 posts
Default

Hello GoSPvC,

I'm still not quite understanding what you are trying to achieve.

It should be that a new window when opened from the Control Center should be started on a new thread.

Then new window would then be running on that thread.

In your script you are creating yet another thread so that you can do some out of sync work and then you want to wait for that work to complete before continuing the thread of the addon window?

(It almost seems as if you are trying to invoke from one thread into itself)

I'm not quite understanding the purpose of this. If the intention is to do work in another thread, why is there a need to wait and return this to a try happening in another thread?

When it comes to custom threading, support for this by NinjaTrader is limited to modifying the UI by invoking the thread of the Control Center, Chart, or other window. Threading can become very complicated quickly and would fall under general C# once getting away from UI changes.
http://ninjatrader.com/support/helpG...-threading.htm

If you addon is the window you are trying to modify, all of that is happening in one thread and there is no need to invoke into another thread.

So with that said, adding a wait is not a guaranteed fix. While its possible the other thread's work will be finished by the time the wait is over, this entirely depends on how much work is being done and how long the wait is. Basically, you are gearing up for a race condition. I would not recommend dispatching into another thread from within a try if you are needing the exception to be handled by that try.
NinjaTrader_ChelseaB is offline  
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
ATR(5)[1] throwing out of range error liborc Indicator Development 5 04-25-2017 08:54 AM
ensuring proper usage of InvokeAsync gubbar924 Indicator Development 2 11-16-2016 06:28 PM
throwing exceptions fbertram Version 8 Beta 1 11-04-2016 09:39 AM
Stop Order throwing error thekreme Strategy Development 4 03-20-2015 06:34 AM


All times are GMT -6. The time now is 01:51 AM.

Futures, foreign currency and options trading contains substantial risk and is not for every investor. An investor could potentially lose all or more than the initial investment. Risk capital is money that can be lost without jeopardizing ones financial security or lifestyle. Only risk capital should be used for trading and only those with sufficient risk capital should consider trading. Past performance is not necessarily indicative of future results. View Full Risk Disclosure.

CFTC Rules 4.41 - Hypothetical or Simulated performance results have certain limitations, unlike an actual performance record, simulated results do not represent actual trading. Also, since the trades have not been executed, the results may have under-or-over compensated for the impact, if any, of certain market factors, such as lack of liquidity. Simulated trading programs in general are also subject to the fact that they are designed with the benefit of hindsight. No representation is being made that any account will or is likely to achieve profit or losses similar to those shown.

This website is hosted and operated by NinjaTrader, LLC (“NT”), a software development company which owns and supports all proprietary technology relating to and including the NinjaTrader trading platform. NT is an affiliated company to NinjaTrader Brokerage (“NTB”), which is a NFA registered introducing broker (NFA #0339976) providing brokerage services to traders of futures and foreign exchange products. This website is intended for educational and informational purposes only and should not be viewed as a solicitation or recommendation of any product, service or trading strategy. No offer or solicitation to buy or sell securities, securities derivative or futures products of any kind, or any type of trading or investment advice, recommendation or strategy, is made, given, or in any manner endorsed by any NT affiliate and the information made available on this Web site is not an offer or solicitation of any kind. Specific questions related to a brokerage account should be sent to your broker directly. The content and opinions expressed on this website are those of the authors and do not necessarily reflect the official policy or position of NT or any of its affiliates. 

Vendors along with their websites, products and services, collectively referred to as (“Vendor Content”), are independent persons or companies that are in no manner affiliated with NT or any if its affiliates. NT or any of its affiliates are not responsible for, do not approve, recommend or endorse any Vendor Content referenced on this website and it’s your sole responsibility to evaluate Vendor Content. Please be aware that any performance information provided by a vendor should be considered hypothetical and must contain the disclosures required by NFA Rule 2-29(c). If you are interested in learning more about, or investigating the quality of, any such Vendor Content you must contact the vendor, provider or seller of such Vendor Content. No person employed by, or associated with, NT or any of its affiliates is authorized to provide any information about any such Vendor Content. Visit the CFTC resources for education regarding the industry and signs of fraud.