循环和线程并行工作

时间:2012-09-24 15:40:04

标签: c# multithreading thread-safety threadpool

我的情况是: 循环和线程正在并行工作..我想停止执行循环,直到线程完成其功能,当线程状态停止时,那时我想进一步执行循环..

            for (int pp = 0; pp < LstIop.Count; pp++)
            {
                oCntrlImageDisplay = new CntrlImageDisplay();
                oCntrlImageEdit = new CntrlImageEdit();
                axAcroPDF1 = new AxAcroPDFLib.AxAcroPDF();
                int pages = ConvertFileIntoBinary(LstIop[pp].Input, oCntrlImageEdit);
                oCntrlImageDisplay.ImgDisplay.Image = LstIop[pp].Output;
                oCntrlImageDisplay.ImgEditor.Image = oCntrlImageDisplay.ImgDisplay.Image;


                if (t1 == null || t1.ThreadState.ToString() == "Stopped")
                {
                    t1 = new Thread(() => convert(pages, LstIop[pp].Input, LstIop[pp].Output, stIop[pp].Temp));
                    t1.SetApartmentState(ApartmentState.STA);
                    t1.IsBackground = true;
                    CheckForIllegalCrossThreadCalls = false;
                    t1.Start();

                }
            }

2 个答案:

答案 0 :(得分:-1)

正如其他人所说的那样,在这里进行线程没有任何意义,但是如果你真的想要它,那就做Async。只需使用.Invoke或.begininvoke后跟.endInvoke

EX:

    delegate void T2();

    static void Main(string[] args)
    {
        T2 Thread = new T2(Work);

        while (true)
        {
            IAsyncResult result = Thread.BeginInvoke(null, null);

            //OTHER WORK TO DO

            Thread.EndInvoke(result);
        }
    }

    static void Work()
    {
       //WORK TO DO
    }

使用委托很好,因为你可以指定返回数据,并发送参数

    delegate double T2(byte[] array,string text, int num);

    static void Main(string[] args)
    {
        T2 Thread = new T2(Work);

        while (true)
        {
            IAsyncResult result = Thread.BeginInvoke(null, null);

            //OTHER WORK TO DO

            double Returned = Thread.EndInvoke(result);
        }
    }

    static double Work(byte[] array, string text, int num)
    {
        // WORK TO DO
        return(3.4);
    }

答案 1 :(得分:-2)

要等待线程完成执行,请调用:

t1.join();