H7 Multithreading and Asynchronous Processing Flashcards
Name at least 3 threadpool methodes:
QueueUserWorkItem GetAvailableThreads GetMaxThreads GetMinThreads SetMaxThreads SetMinThreads
What is the most importend methode of the Threadpool.
public static bool QueueUserWorkItem(WaitCallback callBack)
public static bool QueueUserWorkItem(WaitCallback callBack, Object state)
public delegate void WaitCallback(Object state)
ThreadPool.QueueUserWorkItem((x) => result += ReadDataFromIO());
Is there a join methode in a threadpool?
No, you have to wait until it is finished.
Which steps do you take for a backgroundworker thread?
DoWork += DoWorkEventHandler methode
when work is done assign the result to : DoWorkEventArgs.Result
RunWorkerCompleted += RunWorkerCompletedEventHandler methode
Check RunWorkerCompletedEventArgs.Error
Optionaly :
WorkerReportsProgress = true
ProgressChanged += ProgressChangedEventHandler methode
start : BackgroundWorkerInstance.RunWorkerAsync()
Give an example of Invoke.
Invoke means : put this methode pointer + (optional argument) in the queue of the thread of the e.g. UI.
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
if (this.InvokeRequired) { this.Invoke( new Action(UpdateLabel), e.Result.ToString()); //this.Invoke(Delegate methode, arguments that are passed to the delegate methode.)
}
else {
UpdateLabel(e.Result.ToString());
}
}
private void UpdateLabel(string text) {
lblResult.Text = text;
}
How do you tell that you are done with the thread?
Thread.Sleep(0);
What is the difference between a foreground and a background thread and how do you make a background thread?
A forground thread blocks the main application thread for exiting until it is finished. A Background thread gets killed if the main application finishes.
MyThreadInstance.IsBackground = true;
What delegate do you use for an instance of a Thread?
Thread myThread = new Thread(NewTreadStart(MethodeName));
How can we give thread controll up for e.g. 200 ms in a loop?
while(true)
{
Task.Sleep(200)
…
}
What delegate do you use for an instance of a Thread with parameters?
private void MytestMethode(object myValue)
{
} private void button1_Click(object sender, EventArgs e) { Thread t = new Thread(new ParameterizedThreadStart(MytestMethode)); t.Start("Peter"); }
How do you make a static field per thread? So 5 threads each having an individual static (non shared) field?
[ThreadStatic]
public static int mystaticvar;
What is actualy a task?
It is a managed threadpool thread.
How can you start a task?
Task.Run(delegate);
How do you tell a task that it uses a action delegate when giving the methode name?
Task t = Task.Run(action:MyMethodeName);
What is a schedular?
The component that places a task in the thread queue.
How do you put a task in the thread queue of the UI?
Task.Factory.StartNew(UpdateLabel,
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext());
Give an example of a async/await methode.
public partial class Form1 : Form { public Form1() { InitializeComponent(); myAsyncMethode(); }
public async void myAsyncMethode() { await ReadDataFromIOAsync(); }
public Task ReadDataFromIOAsync() { return Task.Run(new Func<double(ReadDataFromIO)); }
public double ReadDataFromIO() { // We are simulating an I/O by putting the current thread to sleep. Thread.Sleep(20000); return 10d; }
Give an example of a async/await methode with a direct await task…
myAsyncMethode();
public async void myAsyncMethode() { //await ReadDataFromIOAsync(); await (Task)Task.Run(new Func(ReadDataFromIO)); }
public Task ReadDataFromIOAsync() { return Task.Run(new Func(ReadDataFromIO)); }
What is the “EventWaitHandle” how does it work?
Create instance of the EventWaitHandle class and use it in the body of a seperate thread execution.
// We use this event to signal when the thread is don executing. EventWaitHandle calculationDone = new EventWaitHandle(false, EventResetMode.ManualReset);
// Create a work item to read from I/O ThreadPool.QueueUserWorkItem((x) => { result += ReadDataFromIO(); calculationDone.Set(); });
//In the main thread: // Wait for the thread to finish calculationDone.WaitOne();
What 2 version of EventWaitHandle are there and what do they do?
EventWaitHandle: AutoResetEvent
Sets the mode to auto reset
EventWaitHandle: ManualResetEvent.
Sets the mode to manual reset.
What is an alternative to EventWaitHandle class with usage of WaitHandle.WaitAll
CoundownEvent Class .NET 4 introduced a new class called CoundownEvent, defined in the System.Threading namespace. The usage scenario is straightforward: You need to wait for a predefined number of threads to finish their work.
How can you implement a thread barrier?
Use the “Barrier” class:
var participants = 5;
Barrier barrier = new Barrier(participants + 1,
// We add one for the main thread.
b => { // This method is only called when all the paricipants arrived.
Console.WriteLine(“{0} paricipants are at rendez-vous point {1}.”,
b.ParticipantCount -1, // We substract the main thread.
b.CurrentPhaseNumber);
});
for (int i = 0; i < participants; i++) { var localCopy = i; Task.Run(() => { Console.WriteLine("Task {0} left point A!", localCopy); Thread.Sleep(1000 * localCopy + 1); // Do some "work" if (localCopy % 2 == 0) { Console.WriteLine("Task {0} arrived at point B!", localCopy); ->barrier.SignalAndWait();barrier.RemoveParticipant();); }
What lock type starts with M… give an example.
object syncObject = new object();
Monitor.Enter(syncObject);
// Code updating some shared data
Monitor.Exit(syncObject);
What is a big risk when using the Monitor class?
Deadlock.
If an exception is thrown after the Monitor.Enter methode then the Monitor.Exit methode is not called, leaving you with a dead lock:
To prevent this:
object syncObject = new object(); Monitor.Enter(syncObject); try { // Code updating some shared data } finally { Monitor.Exit(syncObject); } ...
What is a c# code snipped for Moni…
object syncObject = new object(); lock (syncObject) { // Code updating some shared data }
Here there will not be a dead lock if an exception is thrown.
what is wrong with lock(this)?
It could cause a deadlock.
public class LockThisBadSample { public void OneMethod() { lock (this) { // Do Something here } } } public class UsingTheLockedObject { public void AnotherMethod(){ LockThisBadSample lockObject = new LockThisBadSample(); lock (lockObject) { // Do something else } } }
How can you make certain opperations atomic therefore removing the need for lock (which is resource intensive).
Use of the Interlocked class.
How can you create a cancelation?
Use :
CancellationTokenSource class and a struct: CancellationToken
You can use a cancelationToken in a methode in a seperate thread.
var tokenSource = new CancellationTokenSource(); CancellationToken myToken = tokenSource .Token;
Can the cancelation token force a thread to stop?
No, the code in the thread can choose to stop (cooperative cancellations).