简体   繁体   中英

Asynchronous Threading

I would please like to know where I can get an example of multithreading or asynchronous threading.

In the application that I am busy with I have to run a thread in the background of my application to fetch a value that is changing. And whenever this value reaches a certain amount then it needs to call another function. All this has to run in the background of the program so that the user can still do something else on the application.

Any examples or links that could help would really be appreciated.

In order to summarize the options, I will try to list them here (maybe it would be a good idea to make this a community wiki).

First of all, you can simply start a function in another thread :

Thread t = new Thread( ThreadProc );
t.Start();
// now you can wait for thread to finish with t.Join() or just continue
// Thread.IsBackground allows to control how thread lifetime influences
// the lifetime of the application

...
static void ThreadProc() {...} // can also be non-static, but for simplicity....

Then you can use BackgroundWorker :

BackgroundWorker bgWorker = new BackgroundWorker();
bgWorker.DoWork += MyFunction;
bgWorker.RunWorkerAsync();

voud MyFunction(object o, DoWorkEventArgs args) {...}

You can use ProgressChanged and RunWorkerCompleted events for more control (as well as WorkerReportsProgress and other properties)

Another option is to use ThreadPool , if your method will not take too much time:

ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));
...
static void ThreadProc(Object stateInfo) { ... }

Yet another option is to call BeginInvoke on a delegate :

public delegate int MyDelegate(...);

MyDelegate del = SomeFunction;                     
IAsyncResult ar = del.BeginInvoke(...);
int result = del.EndInvoke(ar);

This will execute on a thread from the thread pool. If you need to wait on calling thread, you can use IAsyncResult.IsCompleted , but it will block the calling thread.

And of course, you can use Task :

var task = Task.Factory.StartNew(() => MyMethod());

This will also execute MyMethod on a thread from the thread pool, so the same warnings apply (although you can use TaskCreationOptions.LongRunning to ensure that the new thread is always created). Under some circumstances (when you wait on task) it can even execute on the same thread, but it is well optimized so you should not worry about that.

This is probably the option with best tradeoff of simplicity vs control (of course, there is no really 'the best'). Here are the benefits (shamelessly stolen from Jon Skeet's answer ):

  • Adding continuations (Task.ContinueWith)
  • Waiting for multiple tasks to complete (either all or any)
  • Capturing errors in the task and interrogating them later
  • Capturing cancellation (and allowing you to specify cancellation to start with)
  • Potentially having a return value
  • Using await in C# 5
  • Better control over scheduling (if it's going to be long-running, say so when you create the task so the task scheduler can take that into account)

Well depending on the level of control that you seek a BackgroundWorker could easily work and its found within the System.ComponentModel.BackgroundWorker . Now here is a link to the MSDN docs on the subject matter : http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

a Simple usecase secenario is like so:

BackgrouWorker BG = new BackgroudWorker();
GB.DoWork += YourFunctionDelegate(object Sender, EventArgs e);
GB.RunWorkerAsync();

Now YourFunctionDelegate(object Sender,EventArgs e) should be what ever it is you want run in the background. However needs to follow this argument form, There are also a good amount of helper functions associated with the backgroundworker like onProgressChanged event that allows monitoring of obviously progress, which if you are new to threading can prove to be a pain at first if you try to make your own threads.

If you would like more control over execution and how the threads function you should take a look at the Task-Parallel-Library here: http://msdn.microsoft.com/en-us/library/dd460717.aspx Which has copious amount of information about multi-threading.

Also here is a great tutorial on how to create a C# thread: http://support.microsoft.com/default.aspx?scid=kb;en-us;815804

For an overview of asynchronous programming on Windows 8 in .Net 4.5:

http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

For .Net 4.0 and older you can use the ThreadPool

    System.Threading.ThreadPool.QueueUserWorkItem(obj =>
    {
        // Do some work
        for (int i = 0; i < 1000; i++)
            Math.Sin(i);

        // Get back to the UI thread
        App.Current.MainWindow.Dispatcher.BeginInvoke(
            new Action(delegate 
            { 
                block.Text = "Done!"; 
            }));
    });

I have a blog post that compares and contrasts various implementations of background tasks , with advantages and disadvantages for each. Spoiler: Task is definitely the best option. Also, I recommend Task.Run over TaskFactory.StartNew .

If your background operation is truly asynchronous, then you may not need any background threading at all. LINQPad has a set of async examples that are a great starting point. These are more up-to-date than the chapter on threading (by the same author) that others have recommended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM