How wrong is the using of such code - c#

I got a code for calling async blocks.
private delegate void MyDelegate();
void Async(MyDelegate t) {
Thread thread = new Thread(new ThreadStart(t));
thread.IsBackground = true;
thread.Start();
}
And then:
Async(delegate() {
// code
});
I'm using it, but I'm sure that this is not the right way to do this. What are the problems with this method?

There seems no point in declaring your own delegate, for one thing. Why not just:
void Async(ThreadStart t) {
Thread thread = new Thread(t);
thread.IsBackground = true;
thread.Start();
}
? Personally I can't see myself wanting to do this often enough (and with no way of finding out how the task is progressing) to warrant a separate method. If you're using .NET 4 you should look into the Task Parallel Library, which still allows you to fire off asynchronous tasks - but in a rather more fully-featured way. (EDIT: Okay, so you can't use that from .NET 2 - it's worth bearing in mind for the future though.)
You might also want to consider using the BeginInvoke method on delegates, which allows you to start them on the thread pool easily anyway - and pass arguments:
Action<string, int> action = (name, age) => { ... };
IAsyncResult result = action.BeginInvoke("Jon", 35, null);
// Now you can use result if you want...
EDIT: You've now said you'll be doing this several times a second. Assuming this is a short-running task, you almost certainly should be using the thread-pool for this. As well as the example above, you can also use ThreadPool.QueueUserWorkItem to add a task to the thread pool. This will be more efficient (through thread reuse) than creating a new thread each time you have a task.

Since you already have a delegate
private delegate void MyDelegate();
you can do this
new MyDelegate(delegate
{
// code
}).BeginInvoke(null, null);
It'd use thread pool threads so you don't wind up overwhelming the runtime with too many threads.

Related

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.

Executing code asynchronously without the help of a second thread?

OK first of all, it's nothing that I need to implement or anything. I just need to know the answer because someone more experienced told me that asynchronous execution doesn't necessarily have to involve a new thread as threads are somewhat heavy constructs, which confused me a lot and I couldn't agree.
Now let's say, I have two methods - Execute() and ExecuteAsync(). Execute() is running on the main thread. I want to call ExecuteAsync() from within Execute() and I don't care whenever it completes executing, but when it does, may be (or may be not) I want use it's return value. That's a typical example of an asynchronous execution, right?
I know I can do this using BackgroundWorker or IAsyncResult (Delegate.BeginInvoke()), but AFAIK under the hood they spawns a secondary CLR Thread/ThreadPool Thread.
So is it anyhow possible to execute the method ExecuteAsync() asynchronously without the help of a second thread?
EDIT : I think this edit will clarify the scenario further. Invoking ExecuteAsync() is NOT the only (or last) task for Execute() to perform. Execute() should continue it's own tasks without caring about the execution of ExecuteAsync() method.
Here is an example of a program that uses asynchrony and never ever uses more than one thread:
public class Foo
{
private int _value;
private TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>();
public int Value
{
get
{
return _value;
}
set
{
_value = value;
var oldTCS = tcs;
tcs = new TaskCompletionSource<bool>();
oldTCS.SetResult(true);
}
}
public Task ValueChanged()
{
return tcs.Task;
}
}
private static void Main(string[] args)
{
Foo foo = new Foo();
foo.ValueChanged()
.ContinueWith(t =>
{
Console.WriteLine(foo.Value);
}, TaskContinuationOptions.ExecuteSynchronously);
foo.Value = 5;
}
The Task returned from ValueChanged will be completed the next time that Value is changed. The user of the Foo class can get that returned task and wire up continuations to run on that task based on an operation that has not yet happened. Then, at some point in the future, the value of foo is changed, and the continuation will run. Note that the foo object could be passed to some other function, entirely unknown to Main, that ends up setting the value (to show why you might want to do something like this).
No new thread is needed to create the Task, nor to execute the continuation.
Here's another example that's much more practical:
We'll start with this simple (extension) method that takes a form and returns a Task indicating when that form is next closed:
public static class FormExtensions
{
public static Task WhenClosed(this Form form)
{
var tcs = new TaskCompletionSource<bool>();
form.FormClosed += (sender, args) => tcs.SetResult(true);
return tcs.Task;
}
}
Now we can have this in one of our forms:
private async void button1_Click(object sender, EventArgs args)
{
Form2 otherForm = new Form2();
otherForm.Show();
await otherForm.WhenClosed();
//take some data from that form and display it on this form:
textBox1.Text = otherForm.Name;
}
Creating and showing another form never involves the creation of new threads. Both this form and the new form use entirely the one UI thread to be created and modified.
The creation of the Task returned from WhenClosed does not need to create a new thread at all.
When the Task is awaited, no new thread is created. The current method ends and the UI thread is left to go back to processing messages. At some point, that same UI thread will do something that results in the second form being closed. That will result in the continuation of the task running, thus returning us to our button click handler where we set the text of the textbox.
All of this is done entirely with the UI thread, no other threads have been created. And yet we've just "waited" (without actually waiting) for a long running operation to finish (the user to put some information into the second form and then close it) without blocking the UI thread, thus keeping the main form responsive.
So is it anyhow possible to execute the method ExecuteAsync() asynchronously without the help of a second thread?
It is possible for some methods to run asynchronously without using a new thread. This can be done via Asynchronous I/O with a signal, for example. Most of the framework's new Async methods added in .NET 4.5 async IO whenever possible instead of threads.
This is why it's a good idea to not assume asynchronous == new thread. While asynchrony can be implemented using threading, it is not always implemented this way. It's better to just think of an asynchronous operation as an operation that (hopefully) will not block, and will complete at some point in the future.
Coroutines are a common way to implement several logical threads using a single physical thread. Older operating systems used this and other related concepts to implement cooperative multitasking.
In this context you may also be interested in continuation-passing style and Eric Lippert has a good blog series on this very topic - Part 1, Part 2, Part 3, Part 4, Part 5.

Microsoft snippet waiting for a System.Threading.Thread to complete

I was looking at the Microsoft MSDN reference page regarding the modifier "volatile", and was a little unsure as to the way in which the snippet they provided, waited for a thread to complete execution.
I know it is only example code, and that the thread completed very quickly, but I believe that the code below is not very good for developers trying to understand threading.
I believe Microsoft have actually presented a code snippet which will introduce a "tight-loop" in the code. Now I appreciate that it will not affect this code snippet (that much), but if a developer takes this code and tries to use it for some multi-threaded code that is a little more intensive, I would presume the "tight-loop" issue would arise?
using System;
using System.Threading;
class Test
{
public static int result;
public static volatile bool finished;
static void Thread2() {
result = 143;
finished = true;
}
static void Main() {
finished = false;
// Run Thread2() in a new thread
new Thread(new ThreadStart(Thread2)).Start();
// Wait for Thread2 to signal that it has a result by setting
// finished to true.
for (;;) {
if (finished) {
Console.WriteLine("result = {0}", result);
return;
}
}
}
}
Snippet reference:
http://msdn.microsoft.com/en-gb/library/aa645755(v=vs.71).aspx
What would be the better way to wait for the thread to finish, in the example above, which would not introduce this "tight-loop" situation?
Or, will a "tight-loop" not actually be introduced at all?
Please note, that the purpose of the snippet is to demonstrate the "volatile" keyword, so using a Thread.Join() would take the snippet out of context I believe.
This snippet doesn't illustrate how to wait, this just illustrates access to a volatile field from different threads.
To wait for your background thread simply, you can use this snippet:
AutoResetEvent autoEvent = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem((o) =>
{
// do your stuff
((AutoResetEvent)o).Set();
}, autoEvent);
autoEvent.WaitOne();
As you say the best way to wait for a thread to finish would be to use Thread.Join or an ManualResetEventSlim event however neither of these would require a volatile bool.
It would be possible to use the code in the example by adding a call to Thread.SpinWait in the loop. This would help to prevent processor starvation. In version 4 of .Net Microsoft added a struct called SpinWait that can be used more effectivly.
There is more information about this in "Threading in C#" by Joseph Albahari

Ensure a Specific Thread runs (acquires a resource) next?

I have a function where I want to execute in a separate thread avoiding two threads to access the same resources. Also I want to make sure that if the thread is currently executing then stop that thread and start executing the new thread. This is what I have:
volatile int threadCount = 0; // use it to know the number of threads being executed
private void DoWork(string text, Action OncallbackDone)
{
threadCount++;
var t = new Thread(new ThreadStart(() =>
{
lock (_lock) // make sure that this code is only accessed by one thread
{
if (threadCount > 1) // if a new thread got in here return and let the last one execute
{
threadCount--;
return;
}
// do some work in here
Thread.Sleep(1000);
OncallbackDone();
threadCount--;
}
}));
t.Start();
}
if I fire that method 5 times then all the threads will be waiting for the lock until the lock is released. I want to make sure that I execute the last thread though. when the threads are waiting to be the owner of the lock how can I determine which will be the next one owning the lock. I want them to own the resource in the order that I created the threads...
EDIT
I am not creating this application with .net 4.0 . Sorry for not mentioning what I was trying to accomplish. I am creating an autocomplete control where I am filtering a lot of data. I don't want the main window to freeze eveytime I want to filter results. also I want to filter results as the user types. If the user types 5 letters at once I want to stop all threads and I will just be interested in the last one. because the lock blocks all the threads sometimes the last thread that I created may own the lock first.
I think you are overcomplicating this. If you are able to use 4.0, then just use the Task Parallel Library. With it, you can just set up a ContinueWith function so that threads that must happen in a certain order are done in the order you dictate. If this is NOT what you are looking for, then I actually would suggest that you not use threading, as this sounds like a synchronous action that you are trying to force into parallelism.
If you are just looking to cancel tasks: then here is a SO question on how to cancel TPL tasks. Why waste the resources if you are just going to dump them all except for the last one.
If you are not using 4.0, then you can accomplish the same thing with a Background Worker. It just takes more boilerplate code to accomplish the same thing :)
I agree with Justin in that you should use the .NET 4 Task Parallel Library. But if you want complete control you should not use the default Task Scheduler, which favors LIFO, but create your own Task Scheduler (http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskscheduler.aspx) and implement the logic that you want to determine which task gets preference.
Using Threads directly is not recommended unless you have deep knowledge of .NET Threading. If you are on .NET 4.0; Tasks and TPL are preferred.
This is what I came up with after reading the links that you guys posted. I guess I needed a Queue therefore I implemented:
volatile int threadCount = 0;
private void GetPredicateAsync(string text, Action<object> DoneCallback)
{
threadCount++;
ThreadPool.QueueUserWorkItem((x) =>
{
lock (_lock)
{
if (threadCount > 1) // disable executing threads at same time
{
threadCount--;
return; // if a new thread is created exit.
// let the newer task do work!
}
// do work in here
Application.Current.Dispatcher.BeginInvoke(new Action(() =>
{
threadCount--;
DoneCallback(Foo);
}));
}
},text);
}

How to guarantee a new thread is created when using the Task.StartNew method

From what I can tell I have misleading bits of information. I need to have a separate thread running in the background.
At the moment I do it like this:
var task = Task.Factory.StartNew
(CheckFiles
, cancelCheckFile.Token
, TaskCreationOptions.LongRunning
, TaskScheduler.Default);//Check for files on another thread
private void CheckFiles()
{
while (!cancelCheckFile.Token.IsCancellationRequested)
{
//do stuff
}
}
This always creates a new thread for me. However after several discussions even if it is marked as LongRunning doesn't guarantee that a new thread will be created.
In the past I have done something like this:
thQueueChecker = new Thread(new ThreadStart(CheckQueue));
thQueueChecker.IsBackground = true;
thQueueChecker.Name = "CheckQueues" + DateTime.Now.Ticks.ToString();
thQueueChecker.Start();
private void CheckQueue()
{
while (!ProgramEnding)
{
//do stuff
}
}
Would you recommend that I go back to this approach to guarantee a new thread is used?
The default task scheduler ThreadPoolTaskScheduler does indeed always create a new thread for long running task. It does not use the thread pool as you can see. It is no different as the manual approach to create the thread by yourself. In theory it could happen that the thread scheduler of .NET 4.5 does something different but in practice it is unlikely to change.
protected internal override void QueueTask(Task task)
{
if ((task.Options & TaskCreationOptions.LongRunning) != TaskCreationOptions.None)
{
new Thread(s_longRunningThreadWork) { IsBackground = true }.Start(task);
}
else
{
bool forceGlobal =
(task.Options & TaskCreationOptions.PreferFairness) != TaskCreationOptions.None;
ThreadPool.UnsafeQueueCustomWorkItem(task, forceGlobal);
}
}
It depends on the Scheduler you use. There are two stock implementations, ThreadPoolTaskScheduler and SynchronizationContextTaskScheduler. The latter doesn't start a thread at all, used by the FromCurrentSynchronizationContext() method.
The ThreadPoolTaskScheduler is what you get. Which indeed uses the LongRunning option, it will use a regular Thread if it set. Important to avoid starving other TP threads. You'll get a TP thread without the option. These are implementation details subject to change without notice, although I'd consider it unlikely anytime soon.
LongRunning is just a hint to the scheduler - if you absolutely must always have a new Thread, you will have to create one.
You'll have to specify why you "always need a separate thread".
void Main()
{
var task = Task.Factory.StartNew(CheckFiles,
cancelCheckFile.Token,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
task.Wait();
}
A smart scheduler will use 1 thread here. Why shouldn't it?
But in general the CheckFiles() method will be executed on another (than the calling) thread. The issue is whether that thread is especially created or whether it might even be executed on several threads (in succession).
When you are using Tasks you give up control over the Thread. And that should be a good thing.

Categories

Resources