Forum Xamarin.iOS
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

InvokeOnMainThread(SetNeedsDisplay) doesn't work

I'm having difficulties with animating Gradient Descent algorithm on UIView. I use Xamarin.iOS, and here's what I have to do:

I have to use UIView as a histogram, draw some dots on histogram by touching the display and then, when i click on "START" button - animation should begin. I have created Windows Forms application in C#.NET and everything works perfect, but the tailor made code for Xamarin.iOS doesn't work. I found out that SetNeedsDisplay() must be called on main thread, so I use InvokeOnMainThread(SetNeedsDisplay). And it works every time (e.g. when painting dots).

But here it doesn't:

public void RunBabyRun()
    _dataSet = new DataSet ( GetInputDataFromTouchSpots (), GetOutputDataFromTouchSpots () ); // initialization of Data Set object
    _gd = new GradientDescent ( _dataSet.GetInputData (), _dataSet.GetOutputData (), _learningRate ); // initialization of Gradient Descent object

    // Don't draw every epoch, it would take an eternity; draw only every moduo-th epochs
    int moduo;
    switch ( PolynomialDegree ) {
        case 1:
            moduo = 10;
        case 2:
            moduo = 500;
        case 3:
            moduo = 100000;
        case 4:
            moduo = 400000;
            moduo = 5000000;

    _isGdRunning = true; // Check in Draw()
    Console.Out.WriteLine("Gradient Descent  >>  Started");
    // _gd.Iteration() updates data (theta parameters); do until convergence
    while ( !_gd.Iteration() )
        if ( _gd.GetEpoch () % moduo == 0 ) {
            InvokeOnMainThread(SetNeedsDisplay); // DOESN'T CALL DRAW() METHOD!!! CALLS WHEN while ENDS
            Console.WriteLine ("Epoch: {0}", _gd.GetEpoch ());

    _isGdRunning = false; // Check in Draw()
    Console.Out.WriteLine ("Gradient Descent  >>  Finished");

Why I can't invoke the Draw() method in while statement? What am I doing wrong?

Thanks in advance,



  • YuriKuznetsovYuriKuznetsov USMember ✭✭✭

    try to use BeginInvokeOnMainThread instead of InvokeOnMainThread, I used SetNeedsDisplay like this BeginInvokeOnMainThread(() => { ViewName.SetNeedsDisplay(); });
    it work well for me

Sign In or Register to comment.