Created
March 30, 2017 14:03
-
-
Save paddykontschak/de9b5b17a47fd037ad709ae0b9f4326b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Threading; | |
// create instance of class `class` | |
Class1 c = new Class1(); | |
private void Start_Thread_Click(object sender, EventArgs e) | |
{ | |
c.frm = this; | |
// create thread1 - similar to class instance, add c.function into brackets | |
Thread t1 = new Thread(c.Machwas); | |
// start thread | |
t1.Start(); | |
// create thread2 and repeat | |
Thread t2 = new Thread(c.Machwas); | |
// start thread | |
t2.Start(); | |
} | |
private void Add_event_Click(object sender, EventArgs e) | |
{ | |
// trigger event | |
c.RaiseCustomEvent += C_RaiseCustomEvent; | |
} | |
private void Delete_event_Click(object sender, EventArgs e) | |
{ | |
// trigger event | |
c.RaiseCustomEvent -= C_RaiseCustomEvent; | |
} | |
private void Stop_Thread_Click(object sender, EventArgs e) | |
{ | |
// stop thread - very easy. literally just setting .Stop to true | |
c.Stop = true; | |
} | |
public void Write(long x) | |
{ | |
// InvokeRequired outputs in which thread the method is being triggered | |
if (this.InvokeRequired) | |
{ | |
// Invoke: synchronious triggering of threads | |
// delegate: "Zeiger auf Objekt, ist typsicher" | |
this.Invoke((MethodInvoker)delegate | |
{ | |
listbox1.Items.Add(x); | |
}); | |
} | |
} | |
---------------------------------- | |
// inside public class Class1 | |
// volatile is a keyword to tell the application that a field can be used by multiple threads simultaneously | |
// fields with volatile aren't being optimized and thus make sure it's always showing the current value | |
public volatile bool Stop = false; | |
public event EventHandler<CustomEventArgs> RaiseCustomEvent; | |
protected virtual void OnRaiseCustomEvent(string msg) | |
{ | |
// create a temp copy of the current event () | |
EventHandler<CustomEventArgs> handler = RaiseCustomEvent; | |
// ... | |
// ... | |
} | |
public void Machwas() | |
{ | |
for (long i = 0; i < 9999999; i++) | |
{ | |
// lock prevents multiple threads to access the method Machwas() simultaneously | |
// once one thread access it the other has to wait | |
lock(this) | |
{ | |
//... | |
// think jQuery's .delay(1000ms) | |
Thread.Sleep(1000); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment