开发者

C#| Program does nothing after thread executed

开发者 https://www.devze.com 2023-04-12 14:40 出处:网络
My thread should return an array-list and put it into files. My problem is that it just stops(at least that\'s how I see it).

My thread should return an array-list and put it into files.

My problem is that it just stops(at least that's how I see it).

Thread:

 ArrayList files = new ArrayList();
            Th开发者_开发百科read getF = new Thread(delegate()
            {
                files = GetFiles(path);
            });
            getF.Start();
            if (getF.ThreadState == ThreadState.Stopped)
            {
                MessageBox.Show(files.Count.ToString());
                foreach (string file in files)
                {
                    if (file != "")
                    {...

getFiles:

ArrayList results = new ArrayList();
            try
            {
             *loops**code*...
            results.Add(srl);//add file to arrFiles
            *end loops*

                MessageBox.Show("Complete");
                return results;
            }

The program just gives me the MessageBox.Show("Complete") and then does nothing. Thanks in advance.


        getF.Start();
        if (getF.ThreadState == ThreadState.Stopped)
        {
           //...
        }

That if() statement will never execute. It takes time for the thread to do its job. You would have to insert getF.Join() but that defeats the point of using a thread.

Use the BackgroundWorker class.


AFAIK, Thread.Start() returns immediately after thread is started. So before checking for ThreadState, you should wait for it to finish work. Waiting for thread to finish was discussed in This question


It's quite likely that the thread won't be finished before you execute the conditional. That is, you have:

getF.Start();
if (getF.ThreadState == ThreadState.Stopped)

It's possible that the thread won't even start before you test to see if it's stopped. You must have some way for the main thread to know that the other one completed its work.

The typical way to wait for a thread to complete is by calling Join. That is:

getf.Start();
getf.Join(); // suspends main thread until the child thread is done

But if you do that, you block your user interface.

The reason for using multiple threads is so that the main thread (the UI thread, in your case) can do other things while the other threads are doing their work. I suspect what you want is a BackgroundWorker that will get the files, and then execute some actions after it's done--in the RunWorkerCompleted event handler.

0

精彩评论

暂无评论...
验证码 换一张
取 消