Monday, 19 May 2014

Cross-thread operation not valid: Control is accessed from a thread other than the thread it was created on.


When you are using threading in your winform application and accessing form controls in method that is called in new thread, then you will face error like below :

Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.

Here is solution for this error. You have to invoke your form again to access controls. Here is snippet for that.


       private void button1_Click(object sender, EventArgs e)
        {
            Thread th = new Thread(setText);
            th.Start();

        }

        public delegate void delTemp();
        public void setText()
        {
            if (this.InvokeRequired)
            {
                delTemp del = new delTemp(setText);
                this.Invoke(del);
                return;
            }
            label1.Text = "This is set from thread";
        }



Friday, 9 May 2014

Search index of value in array using Binary Search

        protected void btnTemp_Click(object sender, EventArgs e)
        {
            int[] intAry = new int[] { 8, 5, 3, 4, 8, 7, 2, 12, 50, 24, 20, 41, 21, 37, 40 };
            intAry = intAry.OrderBy(t => t).ToArray();
            int index = BinarySearch(intAry, Convert.ToInt32(txtSec.Value));
        }

        int BinarySearch(int[] aryNum, int val)
        {
            int index = -1;
            int start, end;
            start = 0;
            end = aryNum.Length;

            while (true)
            {
                int Mid = (end + start) / 2;               

                if (aryNum[Mid] == val)
                {
                    index = Mid;
                    return index;
                }
                else if (aryNum[Mid] > val)
                {
                    end = Mid - 1;                  
                }
                else if (aryNum[Mid] < val)
                {
                    start = Mid + 1;                  
                }
                if (start == end)
                {
                    if (aryNum[start] == val)
                    {
                        index = start;
                        return index;
                    }
                    break;
                }
            }
            return index;

        }