multithreading - C# callback on new thread -
i having trouble creating callback on newly started thread.
i have 2 classes, api, , form.cs. start thread running method in api, form.cs, want notify method in form.cs inside method in api.
i familiar delegation in obj-c, not in c#.
i included relevant code.
public partial class main: form { private api connect = new api(); private void startstopbutton_click(object sender, eventargs e) { //new thread thread threadconnect = new thread(connect.startattemptingwithusername); threadconnect.start(); } public void attemptingwithpasswordmessage(string password) { // want notify method api } } class api : useragent { public void startattemptingwithusername() { _shouldstop = false; while (!_shouldstop) { console.writeline(username); // how notify attemptingwithpasswordmessage here? system.threading.thread.sleep(1000); } } }
provide event other class, , fire event whenever relevant based on processing:
class api : useragent { public event action<string> someevent;//todo give better name public void startattemptingwithusername() { _shouldstop = false; while (!_shouldstop) { console.writeline(username); var handler = someevent; if (handler != null) handler("asdf"); // how notify attemptingwithpasswordmessage here? system.threading.thread.sleep(1000); } } }
then add handler event: (and marshal ui thread)
private void startstopbutton_click(object sender, eventargs e) { //new thread thread threadconnect = new thread(connect.startattemptingwithusername); threadconnect.start(); connect.someevent += (data) => invoke( new action(()=>attemptingwithpasswordmessage(data))); }
Comments
Post a Comment