c# - Change main class attributes from Thread -


i'm looking answer long, haven't find answer how should communication between threads/main thread , run-time created threads like. had problem in java , comes in c#.

let's write c# application, has form simple text label , want run thread(s) increments numeric value written in label. i'm creating main class form, , thread's class. i'm creating new object of thread's class in main class , starting thread on it.

how can change text of label defined in main?

so if understand correctly, you're asking how change gui thread.

this done through construct called synchronizationcontext, provides way run code on thread. in case, if wanted change text of label defined in gui thread, take synchronizationcontext corresponding gui thread , post code through other thread.

another concept have familiar tasks. task abstraction that's functionally same thing thread. 2 tasks can run @ same time. task.run starts new task workload represented function.

with said, here's example in wpf:

public class mainwindow {     public mainwindow()     {         initializecomponent();     }      private void button_click(object sender, routedeventargs e)     {         var context = synchronizationcontext.current;          task.run(() => context.post(state => button.content = "hello world!"));     } } 

notice though i'm inside task.run (which means i'm not on gui thread), i'm still able execute code on button posting window's synchroniztaioncontext.


edit: if you're not comfortable task yet, , you'd use thread instead, may able well:

var context = synchronizationcontext.current;  var thread = new thread(() => context.post(state => button.content = "hello world!"));  thread.start(); 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -