{"id":10753,"date":"2022-09-24T21:28:20","date_gmt":"2022-09-24T15:58:20","guid":{"rendered":"http:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/"},"modified":"2022-09-24T21:28:20","modified_gmt":"2022-09-24T15:58:20","slug":"solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/","title":{"rendered":"[Solved] How to create and use background thread to change object from another thread"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-36750307\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"36750307\" data-parentid=\"36750001\" data-score=\"1\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>A background thread is scoped to the main thread. So it&#8217;ll run as long as the console app is alive. .Net has a rich threading library, so I leave it up to you. <\/p>\n<p>for ex)<br \/>\n1) use a delegate and call BeginInvoke<br \/>\n2) system.threading.Thread namespace<br \/>\n3) System.Threading.Tasks namespace<\/p>\n<p>Since threading can be daunting, here&#8217;s a sample console app that should do almost what you need. <\/p>\n<p>run the app and once your comfy with the basics, you can write your own.<\/p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Threading;\n\n\/\/\/ &lt;summary&gt;\n\/\/\/ Represent a hard working employee.\n\/\/\/ \n\/\/\/ The employee will process a job, once it comes in.\n\/\/\/ \n\/\/\/ \n\/\/\/ &lt;\/summary&gt;\npublic class Employee\n{\n    private Queue&lt;string&gt; _tasksTray;\n    private string _employeeID;\n\n    public Employee(string employeeID, Queue&lt;string&gt; taskTray)\n    {\n        \/\/employee's ID number.  \n        this._employeeID = employeeID;\n\n        \/\/get a reference to the task tray\n        this._tasksTray = taskTray;\n\n        \/\/fire up a worker thread\n        var thread = new Thread(new ThreadStart(this.Run));\n        thread.IsBackground = true;\n        thread.Start();\n    }\n\n    private void Run()\n    {\n        string myTask = null;\n\n        \/\/time to work until i die\n        while (true)\n        {\n            \/\/discard the old task, if any\n            myTask = string.Empty;\n\n            \/\/check if we have anything to do\n            if (this._tasksTray.Count == 0)\n            {\n                lock (this._tasksTray)\n                {\n                    \/\/no jobs; time to chill.\n                    Console.WriteLine(\"Employee# {0} is taking a break.\", this._employeeID);\n                    Monitor.Wait(this._tasksTray);\n                }\n            }\n\n            \/\/work finally came in. Grab the tray and get a task.\n            lock (this._tasksTray)\n            {\n                if (this._tasksTray.Count &gt; 0)\n                {\n                    \/\/yes, i got a job. Remove the task from the tray, so no one else can get it.\n                    myTask = this._tasksTray.Dequeue();\n                }\n            }\n\n            \/\/time to process the task\n            if (!string.IsNullOrEmpty(myTask))\n            {\n                Console.WriteLine(\"Employee# {0} has completed job: {1}.\", this._employeeID, myTask);\n                Thread.Sleep(1000);\n            }\n        }\n    }\n}\n\n\/\/\/ &lt;summary&gt;\n\/\/\/ Represent your standard manager that manages a tray of jobs.\n\/\/\/  \n\/\/\/ for ex)\n\/\/\/ 1) he has a certain number of employees.\n\/\/\/ 2) he interacts with clients and get jobs\n\/\/\/ 3) he post jobs to JIRA and notifies his employees to start working.\n\/\/\/ &lt;\/summary&gt;\npublic class Manager\n{\n    private Queue&lt;string&gt; _taskTray;\n    private List&lt;Employee&gt; _employees;\n\n    public Manager(int numOfEmployees = 5)\n    {\n        \/\/Tray of jobs. This is a shared resource between the manager and employees, so we have to make sure only one person access it at any time.\n        this._taskTray = new Queue&lt;string&gt;();\n\n        \/\/set employees\n        this._employees = new List&lt;Employee&gt;();\n        for (var i = 0; i &lt; numOfEmployees; i++)\n        {\n            this._employees.Add(new Employee(i.ToString(), this._taskTray));\n        }\n    }\n\n    public void AddTask(params string[] newTasks)\n    {\n        lock (this._taskTray)\n        {\n            \/\/add new tasks to the tray\n            foreach (var task in newTasks)\n            {\n                this._taskTray.Enqueue(task);\n            }\n\n\n            \/\/break time over. time to get back to work.\n            Console.WriteLine(\"\\nManager said: Wake up. Time to work. We got {0} jobs.\\n\", newTasks.Length);\n            Monitor.PulseAll(this._taskTray);\n        }\n    }\n\n}\n\n\n\/\/Main\nclass Program\n{\n\n    static void Main(string[] args)\n    {\n        try\n        {\n            \/\/create a manager\n            var manager = new Manager(3);\n\n            \/\/add jobs\n            manager.AddTask(\"Task 1\", \"task 2\");\n\n            \/\/simulate downtime\n            Thread.Sleep(5000);\n\n            \/\/add more jobs\n            var jobs = new List&lt;string&gt;();\n            for (int i = 0; i &lt; 10; i++)\n            {\n                jobs.Add(\"Project# \" + i.ToString());\n            }\n            manager.AddTask(jobs.ToArray());\n\n        }\n        catch (Exception ex)\n        {\n\n            Console.WriteLine(ex.Message);\n        }\n\n        Console.WriteLine(\"press any key to end the program.\");\n        Console.Read();\n    }\n\n\n}\n<\/code><\/pre>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\"><\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved How to create and use background thread to change object from another thread <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] A background thread is scoped to the main thread. So it&#8217;ll run as long as the console app is alive. .Net has a rich threading library, so I leave it up to you. for ex) 1) use a delegate and call BeginInvoke 2) system.threading.Thread namespace 3) System.Threading.Tasks namespace Since threading can be daunting, here&#8217;s &#8230; <a title=\"[Solved] How to create and use background thread to change object from another thread\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/\" aria-label=\"More on [Solved] How to create and use background thread to change object from another thread\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[2945,324,884],"class_list":["post-10753","post","type-post","status-publish","format-standard","hentry","category-solved","tag-background-process","tag-c","tag-multithreading"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] How to create and use background thread to change object from another thread - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] How to create and use background thread to change object from another thread - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] A background thread is scoped to the main thread. So it&#8217;ll run as long as the console app is alive. .Net has a rich threading library, so I leave it up to you. for ex) 1) use a delegate and call BeginInvoke 2) system.threading.Thread namespace 3) System.Threading.Tasks namespace Since threading can be daunting, here&#8217;s ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-09-24T15:58:20+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] How to create and use background thread to change object from another thread\",\"datePublished\":\"2022-09-24T15:58:20+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/\"},\"wordCount\":113,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"background-process\",\"c++\",\"multithreading\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/\",\"name\":\"[Solved] How to create and use background thread to change object from another thread - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-09-24T15:58:20+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] How to create and use background thread to change object from another thread\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] How to create and use background thread to change object from another thread - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] How to create and use background thread to change object from another thread - JassWeb","og_description":"[ad_1] A background thread is scoped to the main thread. So it&#8217;ll run as long as the console app is alive. .Net has a rich threading library, so I leave it up to you. for ex) 1) use a delegate and call BeginInvoke 2) system.threading.Thread namespace 3) System.Threading.Tasks namespace Since threading can be daunting, here&#8217;s ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/","og_site_name":"JassWeb","article_published_time":"2022-09-24T15:58:20+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] How to create and use background thread to change object from another thread","datePublished":"2022-09-24T15:58:20+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/"},"wordCount":113,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["background-process","c++","multithreading"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/","url":"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/","name":"[Solved] How to create and use background thread to change object from another thread - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-09-24T15:58:20+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-how-to-create-and-use-background-thread-to-change-object-from-another-thread\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] How to create and use background thread to change object from another thread"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775193939","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/10753","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=10753"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/10753\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=10753"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=10753"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=10753"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}