H7 Multithreading and Asynchronous Processing Flashcards

1
Q

Name at least 3 threadpool methodes:

A
QueueUserWorkItem
GetAvailableThreads
GetMaxThreads
GetMinThreads
SetMaxThreads
SetMinThreads
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the most importend methode of the Threadpool.

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Is there a join methode in a threadpool?

A

No, you have to wait until it is finished.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Which steps do you take for a backgroundworker thread?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Give an example of Invoke.

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you tell that you are done with the thread?

A

Thread.Sleep(0);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the difference between a foreground and a background thread and how do you make a background thread?

A

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;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What delegate do you use for an instance of a Thread?

A

Thread myThread = new Thread(NewTreadStart(MethodeName));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How can we give thread controll up for e.g. 200 ms in a loop?

A

while(true)
{

Task.Sleep(200)

}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What delegate do you use for an instance of a Thread with parameters?

A

private void MytestMethode(object myValue)
{

    }

    private void button1_Click(object sender, EventArgs e)
    {

        Thread t = new Thread(new ParameterizedThreadStart(MytestMethode));

        t.Start("Peter");
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How do you make a static field per thread? So 5 threads each having an individual static (non shared) field?

A

[ThreadStatic]

public static int mystaticvar;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is actualy a task?

A

It is a managed threadpool thread.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How can you start a task?

A

Task.Run(delegate);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you tell a task that it uses a action delegate when giving the methode name?

A

Task t = Task.Run(action:MyMethodeName);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is a schedular?

A

The component that places a task in the thread queue.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you put a task in the thread queue of the UI?

A

Task.Factory.StartNew(UpdateLabel,
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext());

17
Q

Give an example of a async/await methode.

A
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;
        }
18
Q

Give an example of a async/await methode with a direct await task…

A

myAsyncMethode();

public async void myAsyncMethode()
        {
            //await ReadDataFromIOAsync();
            await (Task)Task.Run(new Func(ReadDataFromIO));
        }
        public Task ReadDataFromIOAsync()
        {
            return Task.Run(new Func(ReadDataFromIO));
        }
19
Q

What is the “EventWaitHandle” how does it work?

A

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();
20
Q

What 2 version of EventWaitHandle are there and what do they do?

A

EventWaitHandle: AutoResetEvent

Sets the mode to auto reset

EventWaitHandle: ManualResetEvent.

Sets the mode to manual reset.

21
Q

What is an alternative to EventWaitHandle class with usage of WaitHandle.WaitAll

A
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.
22
Q

How can you implement a thread barrier?

A

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

What lock type starts with M… give an example.

A

object syncObject = new object();
Monitor.Enter(syncObject);
// Code updating some shared data
Monitor.Exit(syncObject);

24
Q

What is a big risk when using the Monitor class?

A

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);
}
...
25
Q

What is a c# code snipped for Moni…

A
object syncObject = new object();
lock (syncObject) {
// Code updating some shared data
}

Here there will not be a dead lock if an exception is thrown.

26
Q

what is wrong with lock(this)?

A

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
}
}
}
27
Q

How can you make certain opperations atomic therefore removing the need for lock (which is resource intensive).

A

Use of the Interlocked class.

28
Q

How can you create a cancelation?

A

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;
29
Q

Can the cancelation token force a thread to stop?

A

No, the code in the thread can choose to stop (cooperative cancellations).