C# Multi-Threading Tutorial

Поділитися
Вставка
  • Опубліковано 25 січ 2025

КОМЕНТАРІ •

  • @BrandonHilde129
    @BrandonHilde129  9 років тому +6

    Thanks guys for all the support on this video. I have been meaning to make another tutorial about sounds and creating uncompressed .wav files. However I have been busy. So Hopefully in the next two-ish weeks.

  • @kentbrook2568
    @kentbrook2568 7 років тому

    Nice demo, easy to understand even without a working sound card. Ignore these silly nit pickers that troll your work and do no work themselves... great stuff, please keep it up!

  • @MauryaSandeep
    @MauryaSandeep 7 років тому

    Awesome. It worked perfectly without any cross thread issues.....

  • @73h73373r357
    @73h73373r357 9 років тому

    A thread is defined as the smallest sequence of instructions that can be managed independently by a scheduler. In other words, a thread is basically, the smallest block of a code of one single program that can be safely executed, then exited, then restarted without corrupting the program. In c# this would be equivalent to a method. Threading is simply the act of timesharing (either with multiple cores, or time sliced within an individual core) multiple threads, which can either be from the same process if functions can be completed in parallel, or from multiple different processes.

  • @garrettcolas
    @garrettcolas 11 років тому

    Keep in mind things like hyper-threading simulate multiple cores. So an i3 processor only has 2 physical cores, but can hyper-thread on each to effectively have 4 cores.

  • @razshneider2375
    @razshneider2375 5 років тому

    i use a canvas for my drawing because of canvas.height but when i do canvas.refresh() to delete the drawings on a different thread it gives me an error
    System.InvalidOperationException: 'Cross-thread operation not valid: Control 'canvas' accessed from a thread other than the thread it was created on.'
    so should i stop using the canvas because you just did it on the form with the this.creategraphics
    but how do i refresh the form then, or get the height and width?

  • @mandarinnu
    @mandarinnu 3 роки тому

    Thank you. A small suggestion: You could do some refactoring, i.e., refactor the thread() and threadb() methods.

  • @spanout
    @spanout 9 років тому

    Great and simple demonstration that makes perfect sense!

  • @ProfFranciscoAraujo
    @ProfFranciscoAraujo 8 років тому +17

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Threading;
    namespace APP1
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }
    Thread th1;
    Thread th2;
    Random rdm;
    private void Form1_Load(object sender, EventArgs e)
    {
    this.WindowState = FormWindowState.Maximized;
    rdm = new Random();
    }
    private void button1_Click(object sender, EventArgs e)
    {
    // var x = MessageBox.Show("Vermelho", "Mensagem");
    th1 = new Thread(thread1);
    th1.Start();
    }
    private void button2_Click(object sender, EventArgs e)
    {
    // var x = MessageBox.Show("Azul", "Mensagem");
    th2 = new Thread(thread2);
    th2.Start();
    }
    public void thread1()
    {
    for (int i = 0; 1 < 100; i++)
    {
    this.CreateGraphics().DrawRectangle(new Pen(Brushes.Red, 4), new Rectangle(rdm.Next(0, this.Width), rdm.Next(0, this.Height), 20, 20));
    Thread.Sleep(100);
    }
    }
    public void thread2()
    {
    for (int i = 0; 1 < 100; i++)
    {
    this.CreateGraphics().DrawRectangle(new Pen(Brushes.Blue, 4), new Rectangle(rdm.Next(0, this.Width), rdm.Next(0, this.Height), 20, 20));
    Thread.Sleep(100);
    }
    }
    private void Form1_Closed(object sender, EventArgs e)
    {
    th1.Abort("Fim th1");
    th2.Abort("Fim th2");
    Environment.Exit(0);
    }
    }
    }

    • @benjaminchiozalde3414
      @benjaminchiozalde3414 7 років тому

      no mames te rifaste

    • @marcohundINV
      @marcohundINV 6 років тому +3

      you misstyped the for loop .. u typed for (int i = 0; 1 < 100; i++) instead of for (int i = 0; i < 100; i++)

  • @ProfFranciscoAraujo
    @ProfFranciscoAraujo 8 років тому

    Wow!
    The best example i'm found!
    Thanks Brandon!

  • @jebclang9403
    @jebclang9403 4 роки тому

    This exact example will only work with 2 CPU cores or more right?
    Otherwise, with 1 core, the 2 threads will only switch back and forth to complete their task in the same time it would take without multi threading.

  • @pebito
    @pebito 8 років тому +14

    This tut is easy to understand, however you should not use variable names like "th" and "th1" not even when demonstrating. Giving "thread" as method name is a bad practice too. Not to mention in C# method names start with uppercase letters. Please follow the naming convention at all times!

  • @sandradebrauwer2401
    @sandradebrauwer2401 4 роки тому

    I tried to run the graphics only in the main loading form but it didnot work, I used no button, perhaps I have to make a button

  • @carlosbvz
    @carlosbvz 10 років тому

    I agree with other commets. Simple and complete.
    Thanks

  • @Ak0tnik
    @Ak0tnik 10 років тому

    Thank you. This helped me a lot with a programming project (need to simulate how a dam gets its water drained on real time)

  • @fntasticHijack
    @fntasticHijack 11 років тому

    Ive tried to test my game, but when the computer thinks for a solution, my game was frozen. Can multi threads solve the problem? or you have another solution for that?

  • @donmohino4414
    @donmohino4414 7 років тому

    Thank you for this great tutorial.
    I am making a serial port data reader and i am having a problem: if i use the serialport.readline method in a thread(like you did in the video), an error shows up.
    This is what the error says: "Invalid inter-thread operation: The 'textBox1' control was accessed from a thread other than the one on which it was created".
    Any ideas the fix this?

  • @killaurnext
    @killaurnext 11 років тому

    nicely done....not too complex and gets the point across

  • @thornphillips1565
    @thornphillips1565 7 років тому

    Hey Brandon thanks for the tutorial. I am very new at programming and I was wondering, as I noticed you created a new thread method for each thread you were running, I couldn't help but to wonder if you could run multiple threads out of one method by maybe creating a new reference to it on each object. Seems like it would make for cleaner code.

  • @aleksandar5323
    @aleksandar5323 10 років тому

    So if I want to set a parameter by the Return of a thread , but try to use this parameter before the thread is finished will it wait until it's done or crash? Only one way to find out :D

  • @RejhanKuch
    @RejhanKuch 8 років тому

    Nice write, thank you for sharing your video, it helped me a lot for some small project about threading I had.

  • @jgmangala
    @jgmangala 9 років тому

    thanks..... with the the things go wrong... it really helps to understand core concept.

  • @ogdencitizensclub
    @ogdencitizensclub 10 років тому

    Thank you very much, the explanation is both simple and complete, it helped a lot.

  • @bedennawulezi6448
    @bedennawulezi6448 7 років тому

    Hello Brandon,
    Thank you for this tutoiral! I´m trying to read a sequence of values in array to my Arduino.
    I´m really not so good with programming. I problem is indeed how by just hitting a button, the arduino could read the values via serial port at a given interval. i.e reading the first row of data from dataTable. After making use of the values (eg. runs motors to position) then it waits for a particular period of time and read again the the 2nd row from the datatable. etc.
    Do u think u could help? I would be so grateful.
    Thank You!
    Bede

  • @marcusrehn
    @marcusrehn 12 років тому

    Threading like this is not hard, but I can never find a good video that includes the sharing of resources between different threads. Thats where it becomes harder.

  • @HawaiianDan123
    @HawaiianDan123 11 років тому

    Very nicely done! Just what I needed.

  • @xarzu
    @xarzu 9 років тому +1

    Good job. Easy to understand.
    And Kudos for debugging on the fly like that.

  • @DanieboyTV
    @DanieboyTV 9 років тому

    Simply following the tutorial gave me an error:
    An unhandled exception of type 'System.NullReferenceException' occurred in Draw thread boxes.exe

    • @SB-hs4yn
      @SB-hs4yn 9 років тому

      +DanieboyTV Check your code for grammatical errors and such.

  • @zzvila
    @zzvila 11 років тому

    How can I do this using Process

  • @leonardshin4469
    @leonardshin4469 8 років тому

    Thank you for explaining beautifully what no one else including my AP comp Sci teacher couldn't explain. However, there is this weird caveat when i press the blue button three or more times. There occurs this error:
    :::::::An unhandled exception of type 'System.InvalidOperationException' occurred in System.Drawing.dll
    :::::::Additional information: Object is currently in use elsewhere.
    I was wondering if there was a way to prevent this from happening or at least why it''s throwing this error. Thank you and it'd be wonderful if you replied (Hint hint :) )

    • @maxratner6141
      @maxratner6141 8 років тому

      multiple things are calling the same DLL at the same time (in the separate threads), could be causing the conflict. Probably want to be checking in your code for these collisions. It's like trying to fit 5 cars into a 2 lane tunnel, I suppose?

  • @Kay-hx8xb
    @Kay-hx8xb 8 років тому

    If I have a function contains parameters like Method(a, b), so how can I initailize the instance of new thread?

    • @BrandonHilde129
      @BrandonHilde129  8 років тому

      You can use a Parameterized ThreadStart to do that. Also you can use static variables that are created out side of the that thread. Hope this helps!

    • @Kay-hx8xb
      @Kay-hx8xb 8 років тому +1

      Ok, I created, initialized and ran it perfectly.
      And I think the way you recommended will work.
      Thank you.

    • @BrandonHilde129
      @BrandonHilde129  8 років тому

      Awesome! glad it worked :)

  • @johnabraham9203
    @johnabraham9203 9 років тому

    application should open with a splash screen that displays a disabled list of days of week for 10secs and proceed to next form

  • @lior19977
    @lior19977 12 років тому

    thanks for the vid.
    can you to make me a tutorial about making sound effects for my games.
    thanks

  • @vincenguyen1356
    @vincenguyen1356 9 років тому

    I learn best with trial and error. Good tutorial Thanks

  • @sazzzz878373478
    @sazzzz878373478 9 років тому

    Can you share this source of this tutorial ?

  • @WoundedEgo
    @WoundedEgo 11 років тому

    Great job on this tutorial buddy, thanks.

  • @sergiopalazzi6033
    @sergiopalazzi6033 6 років тому

    Great tutorial. Good explanations! Thanks a lot.

  • @chrisjohnson7255
    @chrisjohnson7255 6 років тому

    Cool stuff I'll probably need this soon.

  • @BrandonHilde129
    @BrandonHilde129  11 років тому

    That is true. however I try to keep my explanations simple. but thanks for the clarity.

  • @SaurabhSashank
    @SaurabhSashank 11 років тому

    This is great stuff dear......

  • @paulcox9728
    @paulcox9728 10 років тому

    good job with this, thanks, subscribed and liked

  • @zillabunny
    @zillabunny 10 років тому

    very nice!

  • @germandiez2974
    @germandiez2974 7 років тому +1

    i'm not making a videogame, but this really help me tahnks man!

  • @djdannyback3455
    @djdannyback3455 9 років тому

    Você poderia me passar o código?

  • @khuyenbuivan7658
    @khuyenbuivan7658 8 років тому

    Thank you. Great video

  • @joacimjohnsson
    @joacimjohnsson 11 років тому

    Hi, Great... I would be interested in a tutorial on how to move the boxes with the mouse. You dont have to go on from this tutorial, you could start simple with moving a box tipsNtricks... thanks Jo

  • @StansPreviouslyOwnedSoundtrack
    @StansPreviouslyOwnedSoundtrack 8 років тому

    Brilliant, thank you!!

  • @madvvasp
    @madvvasp 9 років тому

    Good tutorial, thank you!
    PS. Try to use GitHub to share the code (do not confuse with Pornhub :) )
    Good luck!

    • @BrandonHilde129
      @BrandonHilde129  9 років тому +5

      +Юрий Руд thanks dude but I think people learn better when they don't copy and paste code. So I prefer that people follow along.

    • @MegaMeno
      @MegaMeno 7 років тому

      Brandon Hilde no, it's actually the other way around. That's why teachers give full examples so the learners can learn better, when the questions come the will know how to solve them because they know their logic.

  • @josemena649
    @josemena649 8 років тому

    can you do pack man game in c# too ?? im a beginer and i lie to learn how to do it PLS
    just a symple code pls

  • @standinonstilts
    @standinonstilts 11 років тому

    Great video!

  • @indrajaya9157
    @indrajaya9157 8 років тому

    ON YOUR CODE AND MY CODE WEWEWW WELL WELL WELL

  • @kernelle4
    @kernelle4 11 років тому

    thank you, you have earned a new sub

  • @ivyliu6182
    @ivyliu6182 11 років тому

    Very useful!

  • @khalilburno9713
    @khalilburno9713 9 років тому

    NICE smart and short tip , thank you ,but the sound is too low i cant here you almost
    thank you thumbs up ;-)

  • @chidhvilaskommineni1466
    @chidhvilaskommineni1466 9 років тому

    good one

  • @4kills482
    @4kills482 7 років тому

    Nice video but you kept repeating that multi threads will make your programm faster.
    This is only partially true. If you run the application on a single core cpu the cpu will process one thread at a time, then halt that first thread to execute the second one etc.. It will not process simultaneiously. Unless you are using multi core cpus threading won't lead to a performance increase.
    Programmers should use threading as often as possible where possible, in order to make use of multi core processors nowadays. A lot of programms are badly written by not distributing workload across multiple processing cores.

  • @garrettcolas
    @garrettcolas 11 років тому

    Come on man, you can't just say programming for the console is worthless. It's very important for business/enterprise applications.

  • @FLneodesign
    @FLneodesign 10 років тому

    Great Video thanks :)

  • @korioss
    @korioss 12 років тому +1

    Ty for the video

  • @ziajunaidi2023
    @ziajunaidi2023 11 років тому

    cool

  • @BrandonHilde129
    @BrandonHilde129  12 років тому

    I just put up a video about playing sound a few days ago... you should check it out

  • @zahidtuhin1407
    @zahidtuhin1407 10 років тому

    nice

  • @Iconejey
    @Iconejey 6 років тому

    very useful thank you! +1 like for me

  • @JOHNDATGOONV2
    @JOHNDATGOONV2 11 років тому

    Thanks so much

  • @TheLosgat
    @TheLosgat 9 років тому

    Tx man..

  • @winterfrog5521
    @winterfrog5521 10 років тому

    please speak loud