【问题标题】:Starting and joining a thread when the thread has starting parameters当线程具有启动参数时启动和加入线程
【发布时间】:2011-10-11 08:33:59
【问题描述】:

在下面的代码中,我将正在拖放到表单上的按钮上的文件,并使用线程处理它们。我希望能够在 foreach 循环继续并处理下一个文件之前让每个线程完成它的操作。

我尝试了

testthread().Join();

就在

new Thread(()...

但它得到一个错误,因为它希望我传递与我传递给测试线程时相同的参数我最初启动线程。

谁能告诉我用于完成线程连接的命令和语法?

private void btnClick_DragDrop(object sender, DragEventArgs e)
{
    string[] file = (string[])e.Data.GetData(DataFormats.FileDrop);

    string ButtonName = "TestButton"

    string[] files = new string[10];

    files = (string[])e.Data.GetData(DataFormats.FileDrop);


    foreach (string file in files)
    {
        FileInfo fileInfo = new FileInfo(file);

        Console.WriteLine("++  Filename: " + fileInfo.Name + "   Date of file: " + fileInfo.CreationTime + "   Type of file: " + fileInfo.Extension + "   Size of file: " + fileInfo.Length.ToString());

        string CleanFileName = System.Web.HttpUtility.UrlEncode(fileInfo.Name.ToString());

        //Start  thread
        try
        {
            Console.WriteLine("++ Calling testthread with these params: false, " + ButtonName + "," + CleanFileName + "," + file);

            new Thread(() => testthread(false, ButtonName, CleanFileName, file)).Start();

            testthread().Join(); //THIS DOES NOT WORK BECAUSE IT WANTS THE PARAMETERS THAT THE THREAD IS EXPECTING.  WHAT CAN I PUT HERE SO IT WAITS FOR THE THREAD TO FINISH BEFORE CONTINUING THE FOREACH LOOP ?
         }
         catch (Exception ipwse)
         {
         Console.WriteLine(ipwse.Message + " " + ipwse.StackTrace);
         }
     }
}
public void testthread(bool CalledfromPendingUploads, string ButtonName, string CleanFileName, string FilePath)
{
    //My Code to do the file processing that I want done.  I do not want multiple threads to run at once here.  I need the thread to complete, then the foreach loop to continue to the next file and then start another thread and wait, etc...
}

【问题讨论】:

  • 启动一个线程然后等待它是没有意义的。直接调用 testthread() 即可。

标签: c# multithreading thread-safety threadpool


【解决方案1】:

如果你是按顺序做事,那为什么还需要单独的线程呢?

Thread t = new Thread(() => testthread(false, ButtonName, CleanFileName, file));
t.Start();
t.Join();

编辑:

另外,您似乎正在 UI 线程上执行 foreach 循环 - 这将阻塞 UI 线程,对于长时间运行的操作而言,这通常不是一件好事。我建议您将循环代码移到您在另一个线程上执行的单独方法中,同时摆脱每个文件处理的单独线程。

【讨论】:

  • 是的,你是对的。我没有思考。我首先在做线程,因为我的 UI 线程被阻塞了。使用 .Join() 违背了这个目的,让我回到了我开始的地方。您说将循环代码移动到单独的方法中。这是否意味着将循环代码移动到它自己的线程中并在循环内完成我所有的文件处理?
【解决方案2】:
var myThread = new Thread(...
myThread.Start();
myThread.Join();

而你所做的是调用线程过程,期望它返回具有名为“Join”的方法的东西。 Join 是 Thread 对象的一个​​方法。构造线程对象并使用它。

【讨论】:

    【解决方案3】:

    线程不是你的答案。如果您需要等待一个线程完成才能开始下一个线程,那么如果您根本不使用线程,您将遇到同样的瓶颈。但是,如果您使用 .NET 4.0,那么并行任务库肯定会帮助您。使用并行任务,您可以让您的 foreach 循环并行运行并加速您的程序。

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多