Assuming the constructive criticism in this thread Thread-safe events - is this a "clean" way? I sat down and tried to read me in the whole thematics of multithreading.
Here's some code with the same base question: Is this an established way to create a non-freezing UI using events?
public partial class Form1 : Form
{
public delegate void MyThreadUpdateHandler(string s);
public event MyThreadUpdateHandler MyThreadUpdate;
System.Threading.Thread MyThread;
public Form1()
{
InitializeComponent();
}
void DoTheCount()
{
int a = 0;
while (a < int.MaxValue)
{
if (a % 1000000 == 0)
{
this.MyThreadUpdate(a.ToString());
}
a++;
}
}
private void Form1_MyThreadUpdate(string s)
{
this.lblEvent.Invoke((MethodInvoker) delegate ()
{
lblEvent.Text = s;
});
}
private void btnStartThread_Click(object sender, EventArgs e)
{
MyThreadUpdate += Form1_MyThreadUpdate;
if (MyThread == null)
MyThread = new System.Threading.Thread(new System.Threading.ThreadStart(DoTheCount));
lblStatus.Text = "Starting thread";
if (MyThread.ThreadState == System.Threading.ThreadState.Unstarted)
MyThread.Start();
}
private void btnAbortThread_Click(object sender, EventArgs e)
{
MyThread.Abort();
}
}
However there's something I still don't get. Why are some examples using a Program() like this one? http://www.codeproject.com/Articles/667298/Using-ThreadStaticAttribute
Thank you :)
However there's something I still don't get. Why are some examples
using a Program() like this one?
http://www.codeproject.com/Articles/667298/Using-ThreadStaticAttribute
the code is
static void Main(string[] args)
{
Program prog = new Program();
//define the threads
Thread thread1 = new Thread(new ThreadStart(prog.ThreadFunc1));
Thread thread2 = new Thread(new ThreadStart(prog.ThreadFunc2));
This allowed the developer to call instance funcitons public void ThreadFunc1() & public void ThreadFunc2()
from static funciton - static void Main(string[] args)
Update 1
Established way to create a non-freezing UI, is to do all the time consuming activity on a separate thread & marshal the call to UI thread only to update to it.
What you have implemented follows the same idea.
Just one point I would like to mention, although it has nothing to do with freezing of UI.
instead of System.Threading.Thread, Please use ThreadPool.
Task, BackgroundWorker, System.Threading.Timer, Asynchronous Programming Model all use a thread from ThreadPool. or you may also use ThreadPool.QueueUserWorkItem
There are very special cases when one should use System.Threading.Thread instead of a thread from ThreadPool
Firstly, let me say, I feel sorry for you, trying to work with a legacy library.
Okay. You qualify for one of the few reasons I would work with threading in .net
Running a Legacy library for a long time
Now, reading your previous code, I feel that you want to use Rx.Net for project.
I would start by creating a IObservable for your library.
public static class LibraryHelper
{
public static IObservable<EventPattern<StatusChangedEventArg>> StatusObservable(this ComLibrary com)
{
return Observable.FromEventPattern<EventHandler<StatusChangedEventArg>, StatusChangedEventArg>(x => com.FooEvent +=x, x => com.FooEvent -= x);
}
}
This shall allow you to use Rx.Net with your library, like so...
private async void btnStartThread_Click(object sender, EventArgs e)
{
ComLibary com = new ComLibray();
lblStatus.Text = "Starting thread";
// using is there to unsubscribe after the call, to prevent a memory leak.
var subscription = com.StatusObservable()
//Magic sauce
//http://stackoverflow.com/questions/7417978/how-to-get-a-winform-synchronization-context-or-schedule-on-a-winform-thread
.ObserveOn(SynchronizationContext.Current)
.Subscribe(#event => {
//Do something on the UI thread
});
using(subscription)
{
//Task.Run uses a background thread to get the data from your COM
var result = await Task.Run(()=> com.Read());
//back in UI thread. Do stuff.
}
}
Related
My question is i want to execute some operations like fetching the data ( format is string )from some URL . and i want run this process to be background. i have to call this operations whenever user needs this. like if a user clicks a button specified for this operation, it should execute the function and provide result to that user. Problem is when ever executing this no other program should not get interrupted. I want to run this Asynchronous way . i want to return the result which is downloaded from the URL
Here is my solution using thread
namespace xyz
{
public class newWinForm : Form
{
SomeClass someClass = new SomeClass();
public newWinForm()
{
Thread backgroundThread = new Thread(DoWork);
backgroundThread.IsBackground = true;
backgroundThread.Start();
}
void DoWork()
{
try
{
Console.WriteLine("Doing some work...");
using(WebClient cl = new WebClient())
{
string result = cl.DownloadString("http://www.......com");
}
Thread.Sleep(1000);
}
finally
{
Console.WriteLine("This should be always executed");
}
}
private void getDataFrmUrlButton_Click(object sender, EventArgs e)
{
Thread backgroundThread = new Thread(DoWork);
backgroundThread.IsBackground = true;
backgroundThread.Start();
}
}
You can use backgroundworker class in order to achieve your task
private BackgroundWorker bg1 = new BackgroundWorker();
bg1.DoWork += bg1_DoWork;
private void bg1_DoWork(object sender, DoWorkEventArgs e)
{
//the function you want to execute
}
In this case your operation is I/O bound, so an asynchronous approach is best. To do this you can use the async keyword on your events.
private async void getDataFrmUrlButton_Click(object sender, EventArgs args)
{
using(var client = new WebClient())
{
string result = await client.DownloadStringTaskAsync(uri);
// Do stuff with data
}
}
This post gives some good resources for more information on async/await.
If you want a more enterprise based solution you can have a look at Hangfire (https://www.hangfire.io/).
While normally targeted at ASP.NET solutions you can also run it as part of a windows service and use that in conjunction with your WinForm based application(s). It will allow you to easily hand off long running tasks and track them even if you don't want to to use TPL to do it yourself.
This question is possibly a duplicate of How do you add a timer to a C# console application and few other similar questions but couldn't find the answer I'm looking for so asking again.
Question: How do you pass data from the Elapsed event of a Timer (System.Timers.Timer) to the thread that created the timer (that thread may not be the Main thread but another thread spawned by Main)?
I assume there could be some trivial way of achieving this eg. like the BackgroundWorker ProgressChanged event being called in the thread that created the worker, but couldn't find a way in MSDN documentation or SO. Most examples I've seen do some action in the timer thread (https://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx) but don't pass anything to the original thread. Needless to say I'm pretty new to C#/.NET so a solution + pointers to references are appreciated.
Edit: I'd prefer not to use the Invoke()/InvokeRequired pattern (cf. How to use safe threading for a timer(Change timer properties from different thread) ) as this is not for a Forms application. I'm tempted to solve this by creating a BackgroundWorker that reports to the original thread at intervals (DoWork will be just a sleep() inside a loop) but thought .NET might have this already and hence the question.
Will you consider use a dispatcher? (although you need invoke some method too)
When some thread (maybe not the main thread) create the timer which you mentioned, you can create the dispatcher with the same thread too. After that, dispatcher.invoke() will let the original thread to do those task for you. See the MSDN for more information.
It seems to me that a simple locking mechanism is what you need:
private Object _sync = new Object();
void MyTimerFinished()
{
lock (_sync)
{
// Access shared data
...
}
}
void CodeExecutingInMainThread()
{
lock (_sync)
{
// Access shared data
...
}
}
Ok, so this is what I came up with (a solution with locks and Queues sounds a bit too complex for me - may be simpler but haven't tried)
public class ReportingTimer
{
public event EventHandler Elapsed;
private int _interval;
private BackgroundWorker _worker;
public ReportingTimer(int interval)
{
_interval = interval;
_worker = new BackgroundWorker();
_worker.WorkerReportsProgress = true;
_worker.WorkerSupportsCancellation = true;
_worker.DoWork += _worker_DoWork;
_worker.ProgressChanged += _worker_ProgressChanged;
}
public void Start()
{
if (!_worker.IsBusy)
{
_worker.RunWorkerAsync();
}
}
public void Stop()
{
if (_worker.IsBusy)
{
_worker.CancelAsync();
}
}
private void _worker_DoWork(object sender, DoWorkEventArgs e)
{
while (!_worker.CancellationPending)
{
Thread.Sleep(_interval);
_worker.ReportProgress(1);
}
if (_worker.CancellationPending)
{
e.Cancel = true;
}
}
private void _worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (!_worker.CancellationPending)
{
if (Elapsed != null)
{
Elapsed(this, new EventArgs());
}
}
}
}
Please critique.
Edit: This serves my purpose and the interface is similar to the Timer class and is actually what I wanted from the stock Timer.
Is there any library class I can use for a buffer in a consumer-producer situation with multiple threads?
I don't very well understand the multithreading ways of C# so thew example of a perfect solution is in Java:
//Thread 1
Buffer buf = new Buffer();
Thread t2 = new Thread(new MyRunnable(buf) );
while(true){
buf.put(foo);
}
}
//MyRunnable
private Buffer buf;
public MyRunnable(Buffer buf){
this.buf = buf;
}
public void run(){
while(!buf.IsFinished()){
foo = buf.take();
dosth(foo);
}
}
System.Collection.Concurrent has a number of implementations of the IProducerConsumerCollection<T> interface (e.g. ConcurrentQueue<T>), which may be of use in your situation.
There is also a BlockingCollection<T> class that lets your thread block while waiting for the input.
You could use .NET 4.0's ConcurrentBag<T> for this. It implements IProducerConsumerCollection<T> which is designed for that.
If order matters, you can look at ConcurrentQueue<T> or ConcurrentStack<T>.
It looks like you're just trying to find a way to do some work in a background thread and pass collected data off to the caller?
You could use the BackgroundWorker class for this. It allows you to create a simple background thread and pass off something back to the caller when you're done.
public class TestClass
{
private BackgroundWorker worker;
public void DoSomeWorkAsync()
{
this.worker = new BackgroundWorker();
this.worker.DoWork += this.OnDoWork;
this.worker.RunWorkerCompleted += this.OnWorkerComplete;
this.worker.RunWorkerAsync();
}
private void OnDoWork(object sender, DoWorkEventArgs e)
{
//do long running process here to pass to calling thread.
//note this will execute on a background thread
DataTable DT = GetSomeData();
e.Result = DT;
}
private void OnWorkerComplete(object sender, RunWorkerCompletedEventArgs e)
{
//note this event is fired on calling thread
if (e.Error != null)
//do something with the error
else if (e.Cancelled)
//handle a cancellation
else
//grab the result
foo = e.Result;
}
}
I have a timer calling a function every 15 minutes, this function counts the amount of lines in my DGV and starts a thread for each lines (of yet another function), said thread parse a web page which can take anywhere from 1 second to 10 second to finish.
Whilst it does work fine as it is with 1-6 rows, anymore will cause the requests to time-out.
I want it to wait for the newly created thread to finish processing before getting back in the loop to create another thread without locking the main UI
for (int x = 0; x <= dataGridFollow.Rows.Count - 1; x++)
{
string getID = dataGridFollow.Rows[x].Cells["ID"].Value.ToString();
int ID = int.Parse(getID);
Thread t = new Thread(new ParameterizedThreadStart(UpdateLo));
t.Start(ID);
// <- Wait for thread to finish here before getting back in the for loop
}
I have googled a lot in the past 24 hours, read a lot about this specific issue and its implementations (Thread.Join, ThreadPools, Queuing, and even SmartThreadPool).
It's likely that I've read the correct answer somewhere but I'm not at ease enough with C# to decypher those Threading tools
Thanks for your time
to avoid the UI freeze the framework provide a class expressly for these purposes: have a look at the BackgroundWorker class (executes an operation on a separate thread), here's some infos : http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
http://msdn.microsoft.com/en-us/magazine/cc300429.aspx
Btw looks if I understand correctly you don't want to parallelize any operation so just wait for the method parsing the page to be completed. Basically for each (foreach look) row of your grid you get the id and call the method. If you want to go parallel just reuse the same foreach loop and add make it Parallel
http://msdn.microsoft.com/en-us/library/dd460720.aspx
What you want is to set off a few workers that do some task.
When one finishes you can start a new one off.
I'm sure there is a better way using thread pools or whatever.. but I was bored so i came up with this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using System.Threading;
namespace WorkerTest
{
class Program
{
static void Main(string[] args)
{
WorkerGroup workerGroup = new WorkerGroup();
Console.WriteLine("Starting...");
for (int i = 0; i < 100; i++)
{
var work = new Action(() =>
{
Thread.Sleep(1000); //somework
});
workerGroup.AddWork(work);
}
while (workerGroup.WorkCount > 0)
{
Console.WriteLine(workerGroup.WorkCount);
Thread.Sleep(1000);
}
Console.WriteLine("Fin");
Console.ReadLine();
}
}
public class WorkerGroup
{
private List<Worker> workers;
private Queue<Action> workToDo;
private object Lock = new object();
public int WorkCount { get { return workToDo.Count; } }
public WorkerGroup()
{
workers = new List<Worker>();
workers.Add(new Worker());
workers.Add(new Worker());
foreach (var w in workers)
{
w.WorkCompleted += (OnWorkCompleted);
}
workToDo = new Queue<Action>();
}
private void OnWorkCompleted(object sender, EventArgs e)
{
FindWork();
}
public void AddWork(Action work)
{
workToDo.Enqueue(work);
FindWork();
}
private void FindWork()
{
lock (Lock)
{
if (workToDo.Count > 0)
{
var availableWorker = workers.FirstOrDefault(x => !x.IsBusy);
if (availableWorker != null)
{
var work = workToDo.Dequeue();
availableWorker.StartWork(work);
}
}
}
}
}
public class Worker
{
private BackgroundWorker worker;
private Action work;
public bool IsBusy { get { return worker.IsBusy; } }
public event EventHandler WorkCompleted;
public Worker()
{
worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(OnWorkerDoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnWorkerRunWorkerCompleted);
}
private void OnWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (WorkCompleted != null)
{
WorkCompleted(this, EventArgs.Empty);
}
}
public void StartWork(Action work)
{
if (!IsBusy)
{
this.work = work;
worker.RunWorkerAsync();
}
else
{
throw new InvalidOperationException("Worker is busy");
}
}
private void OnWorkerDoWork(object sender, DoWorkEventArgs e)
{
work.Invoke();
work = null;
}
}
}
This would be just a starting point.
You could start it off with a list of Actions and then have a completed event for when that group of actions is finished.
then at least you can use a ManualResetEvent to wait for the completed event.. or whatever logic you want really.
Call a method directly or do a while loop (with sleep calls) to check the status of the thread.
There are also async events but the would call another method, and you want to continue from the same point.
I have no idea why the requests would timeout. That sounds like a different issue. However, I can make a few suggestions regarding your current approach.
Avoid creating threads in loops with nondeterministic bounds. There is a lot of overhead in creating threads. If the number of operations is not known before hand then use the ThreadPool or the Task Parallel Library instead.
You are not going to get the behavior you want by blocking the UI thread with Thread.Join. The cause the UI to become unresponsive and it will effectively serialize the operations and cancel out any advantage you were hoping to gain with threads.
If you really want to limit the number of concurrent operations then a better solution is to create a separate dedicated thread for kicking off the operations. This thread will spin around a loop indefinitely waiting for items to appear in a queue and when they do it will dequeue them and use that information to kick off an operation asynchronously (again using the ThreadPool or TPL). The dequeueing thread can contain the logic for limiting the number of concurrent operations. Search for information regarding the producer-consumer pattern to get a better understand of how you can implement this.
There is a bit of a learning curve, but who said threading was easy right?
If I understand correctly, what you're currently doing is looping through a list of IDs in the UI thread, starting a new thread to handle each one. The blocking issue you're seeing then could well be that it's taking too many resources to create unique threads. So, personally (without knowing more) would redesign the process like so:
//Somewhere in the UI Thread
Thread worker = new Thread(new ParameterizedThreadStart(UpdateLoWorker));
worker.Start(dataGridFollow.Rows);
//worker thread
private void UpdateLoWorker(DataRowCollection rows)
{
foreach(DataRow r in rows){
string getID = r.Cells["ID"].Value.ToString();
int ID = int.Parse(getID);
UpdateLo(ID);
}
}
Here you'd have a single non-blocking worker which sequentially handles each ID.
Consider using Asynchronous CTP. It's an asynch pattern Microsoft recently released for download. It should simplify asynch programming tremendouesly. The link is http://msdn.microsoft.com/en-us/vstudio/async.aspx. (Read the whitepaper first)
Your code would look something like the following. (I've not verified my syntax yet, sorry).
private async Task DoTheWork()
{
for(int x = 0; x <= dataGridFollow.Rows.Count - 1; x++)
{
string getID = dataGridFollow.Rows[x].Cells["ID"].Value.ToString();
int ID = int.Parse(getID);
task t = new Task(new Action<object>(UpdateLo), ID);
t.Start();
await t;
}
}
This method returns a Task that can be checked periodically for completion. This follows the pattern of "fire and forget" meaning you just call it and presumably, you don't care when it completes (as long as it does complete before 15 minutes).
EDIT
I corrected the syntax above, you would need to change UpdateLo to take an object instead of an Int.
For a simple background thread runner that will run one thread from a queue at a time you can do something like this:
private List<Thread> mThreads = new List<Thread>();
public static void Main()
{
Thread t = new Thread(ThreadMonitor);
t.IsBackground = true;
t.Start();
}
private static void ThreadMonitor()
{
while (true)
{
foreach (Thread t in mThreads.ToArray())
{
// Runs one thread in the queue and waits for it to finish
t.Start();
mThreads.Remove(t);
t.Join();
}
Thread.Sleep(2000); // Wait before checking for new threads
}
}
// Called from the UI or elsewhere to create any number of new threads to run
public static void DoStuff()
{
Thread t = new Thread(DoCorestuff);
t.IsBackground = true;
mActiveThreads.Add(t);
}
public static void DoStuffCore()
{
// Your code here
}
I have a bit of code that I need to run in a different thread than the GUI as it currently causes the form to freeze whilst the code runs (10 seconds or so).
Assume I have never created a new thread before; what's a simple/basic example of how to do this in C# and using .NET Framework 2.0 or later?
Good place to start reading is Joe Albahari.
If you want to create your own thread, this is as simple as it gets:
using System.Threading;
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
/* run your code here */
Console.WriteLine("Hello, world");
}).Start();
BackgroundWorker seems to be best choice for you.
Here is my minimal example. After you click on the button the background worker will begin working in background thread and also report its progress simultaneously. It will also report after the work completes.
using System.ComponentModel;
...
private void button1_Click(object sender, EventArgs e)
{
BackgroundWorker bw = new BackgroundWorker();
// this allows our worker to report progress during work
bw.WorkerReportsProgress = true;
// what to do in the background thread
bw.DoWork += new DoWorkEventHandler(
delegate(object o, DoWorkEventArgs args)
{
BackgroundWorker b = o as BackgroundWorker;
// do some simple processing for 10 seconds
for (int i = 1; i <= 10; i++)
{
// report the progress in percent
b.ReportProgress(i * 10);
Thread.Sleep(1000);
}
});
// what to do when progress changed (update the progress bar for example)
bw.ProgressChanged += new ProgressChangedEventHandler(
delegate(object o, ProgressChangedEventArgs args)
{
label1.Text = string.Format("{0}% Completed", args.ProgressPercentage);
});
// what to do when worker completes its task (notify the user)
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
delegate(object o, RunWorkerCompletedEventArgs args)
{
label1.Text = "Finished!";
});
bw.RunWorkerAsync();
}
Note:
I put everything in single method
using C#'s anonymous method for
simplicity but you can always pull
them out to different methods.
It is safe to update GUI within
ProgressChanged or
RunWorkerCompleted handlers.
However, updating GUI from DoWork
will cause
InvalidOperationException.
The ThreadPool.QueueUserWorkItem is pretty ideal for something simple. The only caveat is accessing a control from the other thread.
System.Threading.ThreadPool.QueueUserWorkItem(delegate {
DoSomethingThatDoesntInvolveAControl();
}, null);
Here is another option:
Task.Run(()=>{
//Here is a new thread
});
Quick and dirty, but it will work:
Using at top:
using System.Threading;
simple code:
static void Main( string[] args )
{
Thread t = new Thread( NewThread );
t.Start();
}
static void NewThread()
{
//code goes here
}
I just threw this into a new console application for an exmaple
Try using the BackgroundWorker class. You give it delegates for what to run, and to be notified when work has finished. There is an example on the MSDN page that I linked to.
If you want to get a value:
var someValue;
Thread thread = new Thread(delegate()
{
//Do somthing and set your value
someValue = "Hello World";
});
thread.Start();
while (thread.IsAlive)
Application.DoEvents();
Put that code in a function (the code that can't be executed on the same thread as the GUI), and to trigger that code's execution put the following.
Thread myThread= new Thread(nameOfFunction);
workerThread.Start();
Calling the start function on the thread object will cause the execution of your function call in a new thread.
Here how can use threads with a progressBar , its just for understing how the threads works, in the form there are three progressBar and 4 button:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Thread t, t2, t3;
private void Form1_Load(object sender, EventArgs e)
{
CheckForIllegalCrossThreadCalls = false;
t = new Thread(birinicBar); //evry thread workes with a new progressBar
t2 = new Thread(ikinciBar);
t3 = new Thread(ucuncuBar);
}
public void birinicBar() //to make progressBar work
{
for (int i = 0; i < 100; i++) {
progressBar1.Value++;
Thread.Sleep(100); // this progressBar gonna work faster
}
}
public void ikinciBar()
{
for (int i = 0; i < 100; i++)
{
progressBar2.Value++;
Thread.Sleep(200);
}
}
public void ucuncuBar()
{
for (int i = 0; i < 100; i++)
{
progressBar3.Value++;
Thread.Sleep(300);
}
}
private void button1_Click(object sender, EventArgs e) //that button to start the threads
{
t.Start();
t2.Start(); t3.Start();
}
private void button4_Click(object sender, EventArgs e)//that button to stup the threads with the progressBar
{
t.Suspend();
t2.Suspend();
t3.Suspend();
}
private void button2_Click(object sender, EventArgs e)// that is for contuniue after stuping
{
t.Resume();
t2.Resume();
t3.Resume();
}
private void button3_Click(object sender, EventArgs e) // finally with that button you can remove all of the threads
{
t.Abort();
t2.Abort();
t3.Abort();
}
}
If you are going to use the raw Thread object then you need to set IsBackground to true at a minimum and you should also set the Threading Apartment model (probably STA).
public static void DoWork()
{
// do some work
}
public static void StartWorker()
{
Thread worker = new Thread(DoWork);
worker.IsBackground = true;
worker.SetApartmentState(System.Threading.ApartmentState.STA);
worker.Start()
}
I would recommend the BackgroundWorker class if you need UI interaction.
// following declaration of delegate ,,,
public delegate long GetEnergyUsageDelegate(DateTime lastRunTime,
DateTime procDateTime);
// following inside of some client method
GetEnergyUsageDelegate nrgDel = GetEnergyUsage;
IAsyncResult aR = nrgDel.BeginInvoke(lastRunTime, procDT, null, null);
while (!aR.IsCompleted) Thread.Sleep(500);
int usageCnt = nrgDel.EndInvoke(aR);
Charles your code(above) is not correct. You do not need to spin wait for completion. EndInvoke will block until the WaitHandle is signaled.
If you want to block until completion you simply need to
nrgDel.EndInvoke(nrgDel.BeginInvoke(lastRuntime,procDT,null,null));
or alternatively
ar.AsyncWaitHandle.WaitOne();
But what is the point of issuing anyc calls if you block? You might as well just use a synchronous call. A better bet would be to not block and pass in a lambda for cleanup:
nrgDel.BeginInvoke(lastRuntime,procDT,(ar)=> {ar.EndInvoke(ar);},null);
One thing to keep in mind is that you must call EndInvoke. A lot of people forget this and end up leaking the WaitHandle as most async implementations release the waithandle in EndInvoke.
another option, that uses delegates and the Thread Pool...
assuming 'GetEnergyUsage' is a method that takes a DateTime and another DateTime as input arguments, and returns an Int...
// following declaration of delegate ,,,
public delegate long GetEnergyUsageDelegate(DateTime lastRunTime,
DateTime procDateTime);
// following inside of some client method
GetEnergyUsageDelegate nrgDel = GetEnergyUsage;
IAsyncResult aR = nrgDel.BeginInvoke(lastRunTime, procDT, null, null);
while (!aR.IsCompleted) Thread.Sleep(500);
int usageCnt = nrgDel.EndInvoke(aR);
There are many ways of running separate threads in .Net, each has different behaviors. Do you need to continue running the thread after the GUI quits? Do you need to pass information between the thread and GUI? Does the thread need to update the GUI? Should the thread do one task then quit, or should it continue running? The answers to these questions will tell you which method to use.
There is a good async method article at the Code Project web site that describes the various methods and provides sample code.
Note this article was written before the async/await pattern and Task Parallel Library were introduced into .NET.
How to: Use a Background Thread to Search for Files
You have to be very carefull with access from other threads to GUI specific stuff (it is common for many GUI toolkits). If you want to update something in GUI from processing thread check this answer that I think is useful for WinForms. For WPF see this (it shows how to touch component in UpdateProgress() method so it will work from other threads, but actually I don't like it is not doing CheckAccess() before doing BeginInvoke through Dispathcer, see and search for CheckAccess in it)
Was looking .NET specific book on threading and found this one (free downloadable). See http://www.albahari.com/threading/ for more details about it.
I believe you will find what you need to launch execution as new thread in first 20 pages and it has many more (not sure about GUI specific snippets I mean strictly specific to threading). Would be glad to hear what community thinks about this work 'cause I'm reading this one. For now looked pretty neat for me (for showing .NET specific methods and types for threading). Also it covers .NET 2.0 (and not ancient 1.1) what I really appreciate.
I'd recommend looking at Jeff Richter's Power Threading Library and specifically the IAsyncEnumerator. Take a look at the video on Charlie Calvert's blog where Richter goes over it for a good overview.
Don't be put off by the name because it makes asynchronous programming tasks easier to code.