2011-03-13 52 views
0

WinForm: 我在我的MainApplication中有一个名为check_news的方法。 如何在每次调用方法时(通过按下按钮或在程序的开始)创建并运行将在后台使用方法的线程?每次我调用特定的方法创建一个新的后台线程

我知道如何创建一个线程,但我怎样才能创建新的线程,每次我调用函数(新线程,因为旧的死了)?

我应该创建一个新的类并使用新的类对象和我需要的方法运行线程吗? 我应该在哪里定义线程?

+0

您将在获取它后显示新闻。首先使用BackgroundWorker类,它可以让你摆脱困境。 – 2011-03-13 16:42:44

回答

1
public void Example() 
    { 
     //call using a thread. 
     ThreadPool.QueueUserWorkItem(p => check_news("title", "news message")); 
    } 

    private void check_news(string news, string newsMessage) 
    { 

    } 
+0

当我这样做时,我得到一个异常“跨线程操作无效”:这是我第一次调用方法,任何想法,为什么我得到异常? – 2011-03-13 16:45:49

+0

是的。您只能从GUI线程更改GUI控件。检查这个问题的解决方案:http://stackoverflow.com/questions/2367718/c-automating-the-invokerequired-code-pattern – jgauffin 2011-03-13 16:54:03

+0

我读链接,但仍然在空白,这是GUI线程?它是主线程吗?如何改变使用其他线程的GUI控件? – 2011-03-13 17:02:44

1

您可以通过编写new Thread(...)在方法内创建一个线程。
...可以是方法名称,委托实例或匿名方法。

该代码每次执行时,都会创建一个新的Thread实例。

请注意,使用ThreadPool代替效率更高。

1

我想最好的方法是将它添加到线程池中,它很容易和快速。

例子:

public static void Main(string[] args) 
{ 
    check_news(); 
} 

private static void check_news() 
{ 
    ThreadPool.QueueUserWorkItem((obj) => 
     { 
      // Fetch the news here 
      Thread.Sleep(1000); // Dummy 
     }); 
} 

或者,如果你真的想自己处理吧,这是你可以使用:

public static void Main(string[] args) 
{ 
    check_news(); 
    Console.ReadKey(); 
} 

private static void check_news() 
{ 
    Thread t = new Thread(() => 
     { 
      // Check news here 
      Thread.Sleep(1000); // Dummy 
     }); 
    t.Priority = ThreadPriority.Lowest; // Priority of the thread 
    t.IsBackground = true; // Set it as background (allows you to stop the application while news is fetching 
    t.Name = "News checker"; // Make it recognizable 
    t.Start(); // And start it 
} 

但你应该知道,这需要较长的时间来启动,它不重用线程,而且它没有真正的优势。

或者,如果你想要更多的控制,你可以使用异步平台:

public static void Main(string[] args) 
{ 
    check_news(); // You can add an argument 'false' to stop it from executing async 
    Console.WriteLine("Done"); 
    Console.ReadKey(); 
} 

public delegate void Func(); 

public static void check_news(bool async = true) 
{ 
    Func checkNewsFunction =() => 
     { 
      //Check news here 
      Thread.Sleep(1000); 
     }; 
    if (async) 
    { 
     AsyncCallback callbackFunction = ar => 
     { 
      // Executed when the news is received 

     }; 
     checkNewsFunction.BeginInvoke(callbackFunction, null); 
    } 
    else 
     checkNewsFunction(); 
} 

注意,在所有例子lambda表达式可以一样好被常规功能取代。但我现在只是使用它们,因为它看起来更好。

相关问题