G
G
Grand Silence2017-02-23 15:19:22
C++ / C#
Grand Silence, 2017-02-23 15:19:22

How to access a class instance from another thread (from the form thread to a new thread)?

Hello. How to access an instance of a class that was created in another thread? In WinForms, calling Invoke is enough to change the component from another thread. I need the same thing, only for my class. What are the ways? Thank you.
Here is an example:

class People() {
  public void Say(string message) {}
}

class Form {	
  public Form() {		
    Task.Factory.StartNew(() => { // или через new Thread().Start
      // :отдельный поток
      People bob = new People();
      bob.Say("Hello");
    }
  }

  void OnButtonClick() {
    // :поток формы
    // Как вызвать bob.Say? чтобы была соблюдена потокобезопасность и в Task и в коде ниже
    bob.Say("Bye");
  }
}

// В дополение
// Пример с Dispatcher на формах, который я имел ввиду
class People() {
  public People(Action action) {
    action(); // потокобезопасный вызов
  }
}

class Form {
  Action action;

  void SafeThreadCall() {
    if (this.InvokeRequired) {			
      this.Invoke(action);
      return;
    }
    this.Text = "New window caption!";
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tom Nolane, 2017-02-23
@tomnolane

Dispatcher.Invoke(()=>{ bob.Say("Bye"); });- ???

S
Stalker_RED, 2017-11-01
@campus1

function getClosestToZero() {
  let numbers = Array.prototype.slice.call(arguments)
  return numbers.reduce((prev, curr) =>
    Math.abs(prev) > Math.abs(curr)
                     ? curr : prev
  , +Infinity)
}
jsfiddle.net/x2erL66q

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question