Click here to Skip to main content
15,887,135 members
Home / Discussions / C#
   

C#

 
GeneralRe: Sum columns from joined tables to get a calculated value using linq to SQL Pin
Member 1246241117-Jul-17 3:01
Member 1246241117-Jul-17 3:01 
AnswerRe: Sum columns from joined tables to get a calculated value using linq to SQL Pin
Nathan Minier17-Jul-17 1:13
professionalNathan Minier17-Jul-17 1:13 
AnswerRe: Sum columns from joined tables to get a calculated value using linq to SQL Pin
Richard Deeming17-Jul-17 1:27
mveRichard Deeming17-Jul-17 1:27 
GeneralRe: Sum columns from joined tables to get a calculated value using linq to SQL Pin
Member 1246241117-Jul-17 12:15
Member 1246241117-Jul-17 12:15 
GeneralRe: Sum columns from joined tables to get a calculated value using linq to SQL Pin
Mycroft Holmes17-Jul-17 14:18
professionalMycroft Holmes17-Jul-17 14:18 
GeneralRe: Sum columns from joined tables to get a calculated value using linq to SQL Pin
Richard Deeming18-Jul-17 0:38
mveRichard Deeming18-Jul-17 0:38 
AnswerRe: Sum columns from joined tables to get a calculated value using linq to SQL Pin
Member 1246241118-Jul-17 10:56
Member 1246241118-Jul-17 10:56 
QuestionWriting to UI Thread in a Real time Application Pin
andycruce16-Jul-17 2:41
andycruce16-Jul-17 2:41 
I am building a system to record 6DOF information during an aerobatic flight. I grab data from a hardware set including an IMU, a GPS and a Baro altimeter and 20 to 30ms intervals. I attempted to use the WinForms Timer to schedule data recording using BW to allow me the collect the data in the DoWork method and then write the data to the WinForm in the WorkCompleted method. All this worked properly but the WinForms timer didn't provide the accuracy for scheduling the data properly.

I did a test using a multimedia timer which provided the necessary update timing accuracy but when I used it to drive a BW the WorkCompleted method was no longer in the UI string and I get an error for trying to access a UI element from outside the UI string. I can make this work doing a BeginInvoke((MethodInvoker) delegate {all updates to UI elements in here}). What I would like to know if there is a way to force the WorkCompleted method back to the UI string. Also, not sure why changing the timer made the BW operation change and no longer have the WorkCompleted method in the UI string.

The code for the program is below. The first set is my code and the second set it the C# code that implements the timer that I got off the internet. I'm not sure I used the

correctly but at least I tried.

Appreciate any suggestions as I am still trying to figure out C# and the .net/Winforms environment.

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace Simple_BW_Timing_with_Winforms
{
    public partial class Form1 : Form
    {
        Stopwatch systemTimer;
        long time1 = 0, time2 = 0;
        public long timeBetweenCalls;
        int count;
        BackgroundWorker updateInfoBW;

        public delegate void _writeForm();

        public readonly MicroLibrary.MicroTimer _microTimer;
//        public BackgroundWorker updateInfoBW;

        public Form1()
        {
            updateInfoBW = new BackgroundWorker();
            updateInfoBW.DoWork += updateInfoDoWork;
            updateInfoBW.RunWorkerCompleted += updateInfoWorkCompleted;

            InitializeComponent();
            systemTimer = new Stopwatch();
            systemTimer.Start();

            _microTimer = new MicroLibrary.MicroTimer();
            _microTimer.MicroTimerElapsed +=
                new MicroLibrary.MicroTimer.MicroTimerElapsedEventHandler(tmrCallBW_tick);
            _microTimer.Interval = 20000;
            _microTimer.Start();


        }
        void tmrCallBW_tick(object sender, EventArgs e)
        {

            time1 = time2;
            time2 = systemTimer.ElapsedMilliseconds;
            timeBetweenCalls = time2 - time1;

            updateInfoBW.RunWorkerAsync();

// QUESTION - HOW CAN I GET updateInfoWorkCompleted to execute in the UI thread


        }


        void updateInfoDoWork(object sender, EventArgs e)
        {
            return;
        }

        void updateInfoWorkCompleted(object sender, EventArgs e)
        {
            count++;
            BeginInvoke((MethodInvoker)delegate
            {
                CallTime.Text = string.Format("{0}", timeBetweenCalls);
                CountBox.Text = string.Format("{0}", count);
            });
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            _microTimer.Abort();
        }

 
    }
}


The code for the MicroTimer is:

C#
<pre>using System;

namespace MicroLibrary
{
    /// <summary>
    /// MicroStopwatch class
    /// </summary>
    public class MicroStopwatch : System.Diagnostics.Stopwatch
    {
        readonly double _microSecPerTick =
            1000000D / System.Diagnostics.Stopwatch.Frequency;

        public MicroStopwatch()
        {
            if (!System.Diagnostics.Stopwatch.IsHighResolution)
            {
                throw new Exception("On this system the high-resolution " +
                                    "performance counter is not available");
            }
        }

        public long ElapsedMicroseconds
        {
            get
            {
                return (long)(ElapsedTicks * _microSecPerTick);
            }
        }
    }

    /// <summary>
    /// MicroTimer class
    /// </summary>
    public class MicroTimer
    {
        public delegate void MicroTimerElapsedEventHandler(
                             object sender,
                             MicroTimerEventArgs timerEventArgs);
        public event MicroTimerElapsedEventHandler MicroTimerElapsed;

        System.Threading.Thread _threadTimer = null;
        long _ignoreEventIfLateBy = long.MaxValue;
        long _timerIntervalInMicroSec = 0;
        bool _stopTimer = true;

        public MicroTimer()
        {
        }

        public MicroTimer(long timerIntervalInMicroseconds)
        {
            Interval = timerIntervalInMicroseconds;
        }

        public long Interval
        {
            get
            {
                return System.Threading.Interlocked.Read(
                    ref _timerIntervalInMicroSec);
            }
            set
            {
                System.Threading.Interlocked.Exchange(
                    ref _timerIntervalInMicroSec, value);
            }
        }

        public long IgnoreEventIfLateBy
        {
            get
            {
                return System.Threading.Interlocked.Read(
                    ref _ignoreEventIfLateBy);
            }
            set
            {
                System.Threading.Interlocked.Exchange(
                    ref _ignoreEventIfLateBy, value <= 0 ? long.MaxValue : value);
            }
        }

        public bool Enabled
        {
            set
            {
                if (value)
                {
                    Start();
                }
                else
                {
                    Stop();
                }
            }
            get
            {
                return (_threadTimer != null && _threadTimer.IsAlive);
            }
        }

        public void Start()
        {
            if (Enabled || Interval <= 0)
            {
                return;
            }

            _stopTimer = false;

            System.Threading.ThreadStart threadStart = delegate()
            {
                NotificationTimer(ref _timerIntervalInMicroSec,
                                  ref _ignoreEventIfLateBy,
                                  ref _stopTimer);
            };

            _threadTimer = new System.Threading.Thread(threadStart);
            _threadTimer.Priority = System.Threading.ThreadPriority.Highest;
            _threadTimer.Start();
        }

        public void Stop()
        {
            _stopTimer = true;
        }

        public void StopAndWait()
        {
            StopAndWait(System.Threading.Timeout.Infinite);
        }

        public bool StopAndWait(int timeoutInMilliSec)
        {
            _stopTimer = true;

            if (!Enabled || _threadTimer.ManagedThreadId ==
                System.Threading.Thread.CurrentThread.ManagedThreadId)
            {
                return true;
            }

            return _threadTimer.Join(timeoutInMilliSec);
        }

        public void Abort()
        {
            _stopTimer = true;

            if (Enabled)
            {
                _threadTimer.Abort();
            }
        }

        void NotificationTimer(ref long timerIntervalInMicroSec,
                               ref long ignoreEventIfLateBy,
                               ref bool stopTimer)
        {
            int  timerCount = 0;
            long nextNotification = 0;

            MicroStopwatch microStopwatch = new MicroStopwatch();
            microStopwatch.Start();

            while (!stopTimer)
            {
                long callbackFunctionExecutionTime =
                    microStopwatch.ElapsedMicroseconds - nextNotification;

                long timerIntervalInMicroSecCurrent =
                    System.Threading.Interlocked.Read(ref timerIntervalInMicroSec);
                long ignoreEventIfLateByCurrent =
                    System.Threading.Interlocked.Read(ref ignoreEventIfLateBy);

                nextNotification += timerIntervalInMicroSecCurrent;
                timerCount++;
                long elapsedMicroseconds = 0;

                while ( (elapsedMicroseconds = microStopwatch.ElapsedMicroseconds)
                        < nextNotification)
                {
                    System.Threading.Thread.SpinWait(10);
                }

                long timerLateBy = elapsedMicroseconds - nextNotification;

                if (timerLateBy >= ignoreEventIfLateByCurrent)
                {
                    continue;
                }

                MicroTimerEventArgs microTimerEventArgs =
                     new MicroTimerEventArgs(timerCount,
                                             elapsedMicroseconds,
                                             timerLateBy,
                                             callbackFunctionExecutionTime);
                MicroTimerElapsed(this, microTimerEventArgs);
            }

            microStopwatch.Stop();
        }
    }

    /// <summary>
    /// MicroTimer Event Argument class
    /// </summary>
    public class MicroTimerEventArgs : EventArgs
    {
        // Simple counter, number times timed event (callback function) executed
        public int  TimerCount { get; private set; }

        // Time when timed event was called since timer started
        public long ElapsedMicroseconds { get; private set; }

        // How late the timer was compared to when it should have been called
        public long TimerLateBy { get; private set; }

        // Time it took to execute previous call to callback function (OnTimedEvent)
        public long CallbackFunctionExecutionTime { get; private set; }

        public MicroTimerEventArgs(int  timerCount,
                                   long elapsedMicroseconds,
                                   long timerLateBy,
                                   long callbackFunctionExecutionTime)
        {
            TimerCount = timerCount;
            ElapsedMicroseconds = elapsedMicroseconds;
            TimerLateBy = timerLateBy;
            CallbackFunctionExecutionTime = callbackFunctionExecutionTime;
        }
    }
}

AnswerRe: Writing to UI Thread in a Real time Application Pin
Gerry Schmitz16-Jul-17 4:49
mveGerry Schmitz16-Jul-17 4:49 
AnswerRe: Writing to UI Thread in a Real time Application Pin
Dave Kreskowiak16-Jul-17 5:28
mveDave Kreskowiak16-Jul-17 5:28 
AnswerRe: Writing to UI Thread in a Real time Application Pin
Alan N16-Jul-17 8:31
Alan N16-Jul-17 8:31 
SuggestionRe: Writing to UI Thread in a Real time Application Pin
BenScharbach12-Aug-17 10:17
BenScharbach12-Aug-17 10:17 
QuestionPaste CF_ENHMETAFILE=14 image file Pin
manuellopes14-Jul-17 11:32
manuellopes14-Jul-17 11:32 
SuggestionRe: Paste CF_ENHMETAFILE=14 image file Pin
Richard MacCutchan14-Jul-17 20:35
mveRichard MacCutchan14-Jul-17 20:35 
GeneralRe: Paste CF_ENHMETAFILE=14 image file Pin
manuellopes15-Jul-17 6:08
manuellopes15-Jul-17 6:08 
GeneralRe: Paste CF_ENHMETAFILE=14 image file Pin
Richard MacCutchan15-Jul-17 6:22
mveRichard MacCutchan15-Jul-17 6:22 
GeneralRe: Paste CF_ENHMETAFILE=14 image file Pin
manuellopes15-Jul-17 6:33
manuellopes15-Jul-17 6:33 
GeneralRe: Paste CF_ENHMETAFILE=14 image file Pin
Richard MacCutchan15-Jul-17 6:53
mveRichard MacCutchan15-Jul-17 6:53 
GeneralRe: Paste CF_ENHMETAFILE=14 image file Pin
manuellopes15-Jul-17 7:38
manuellopes15-Jul-17 7:38 
GeneralRe: Paste CF_ENHMETAFILE=14 image file Pin
Richard MacCutchan15-Jul-17 20:30
mveRichard MacCutchan15-Jul-17 20:30 
QuestionServicePointManager and TLS1.2 with Gmail Pin
jkirkerx13-Jul-17 6:34
professionaljkirkerx13-Jul-17 6:34 
AnswerServicePoint, Address = 'smtpClient.ServicePoint.Address' threw an exception of type 'System.NotSupportedException', Pin
jkirkerx13-Jul-17 8:45
professionaljkirkerx13-Jul-17 8:45 
GeneralRe: ServicePoint, Address = 'smtpClient.ServicePoint.Address' threw an exception of type 'System.NotSupportedException', Pin
Richard Deeming13-Jul-17 9:52
mveRichard Deeming13-Jul-17 9:52 
GeneralRe: ServicePoint, Address = 'smtpClient.ServicePoint.Address' threw an exception of type 'System.NotSupportedException', Pin
jkirkerx13-Jul-17 11:38
professionaljkirkerx13-Jul-17 11:38 
GeneralRe: ServicePoint, Address = 'smtpClient.ServicePoint.Address' threw an exception of type 'System.NotSupportedException', Pin
jkirkerx13-Jul-17 12:14
professionaljkirkerx13-Jul-17 12:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.