0

WinForm: I have a method called check_news in my MainApplication. How can I create and run a Thread that will work on the method on background each time I call the method (by pushing a button, or in the start of the program)?

I know how to create a thread but how can I create new thread every time I call the function (new thread because the old one is dead)?

Should I create a new class and run the thread with the new class object and the method I need? Where should I define the thread?

TrueWill
  • 25,132
  • 10
  • 101
  • 150
Michael A
  • 5,770
  • 16
  • 75
  • 127
  • You are going to want to display the news after getting it. Use the BackgroundWorker class first, it keeps you out of trouble. – Hans Passant Mar 13 '11 at 16:42

3 Answers3

1

You can just create a thread inside the method by writing new Thread(...).
The ... can be a method name, delegate instance, or anonymous method.

Each time this code executes, it will create a new Thread instance.

Note that it will be more efficient to use the ThreadPool instead.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

I suppose the best way to achieve this is by adding it to the thread pool, it's easy and quick.

Example:

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

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

Or if you really want to deal with it yourself, this is something you could use:

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
}

But you should know that this takes a longer time to start, it doesn't reuse threads, and there's not a real advantage in it.

Or if you want more control you could use the async platform:

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();
}

Note that the lambda expressions in all examples can just as well be replaced by regular functions. But I just use them right now, because it seems nicer as example.

Aidiakapi
  • 6,034
  • 4
  • 33
  • 62
1
    public void Example()
    {
        //call using a thread.
        ThreadPool.QueueUserWorkItem(p => check_news("title", "news message"));
    }

    private void check_news(string news, string newsMessage)
    {

    }
jgauffin
  • 99,844
  • 45
  • 235
  • 372
  • When doing that i get an exception "Cross-thread operation not valid": this is the first time i call the method, any ideas why i get the exception? – Michael A Mar 13 '11 at 16:45
  • Yes. You can only change GUI controls from the GUI thread. Check this question for a solution: http://stackoverflow.com/questions/2367718/c-automating-the-invokerequired-code-pattern – jgauffin Mar 13 '11 at 16:54
  • I read the link but still on the blank, wht is the GUI thread? is it the main thread? how can one change GUI controls using other thread? – Michael A Mar 13 '11 at 17:02
  • GUI thread = main thread. Here is a more detailed explanation of `InvocationRequired`: http://weblogs.asp.net/justin_rogers/pages/126345.aspx – jgauffin Mar 13 '11 at 17:16