How do I run a simple bit of code in a new thread?

2019-01-02 19:31发布

I have a bit of code that I need to run in a different thread than the GUI as it currently causes the form to freeze whilst the code runs (10 seconds or so).

Assume I have never created a new thread before; what's a simple/basic example of how to do this in C# and using .NET Framework 2.0 or later?

15条回答
梦该遗忘
2楼-- · 2019-01-02 19:56

If you want to get a value:

var someValue;

Thread thread = new Thread(delegate()
            {                 
                //Do somthing and set your value
                someValue = "Hello World";
            });

thread.Start();

while (thread.IsAlive)
  Application.DoEvents();
查看更多
无与为乐者.
3楼-- · 2019-01-02 20:00

How to: Use a Background Thread to Search for Files

You have to be very carefull with access from other threads to GUI specific stuff (it is common for many GUI toolkits). If you want to update something in GUI from processing thread check this answer that I think is useful for WinForms. For WPF see this (it shows how to touch component in UpdateProgress() method so it will work from other threads, but actually I don't like it is not doing CheckAccess() before doing BeginInvoke through Dispathcer, see and search for CheckAccess in it)

Was looking .NET specific book on threading and found this one (free downloadable). See http://www.albahari.com/threading/ for more details about it.

I believe you will find what you need to launch execution as new thread in first 20 pages and it has many more (not sure about GUI specific snippets I mean strictly specific to threading). Would be glad to hear what community thinks about this work 'cause I'm reading this one. For now looked pretty neat for me (for showing .NET specific methods and types for threading). Also it covers .NET 2.0 (and not ancient 1.1) what I really appreciate.

查看更多
无色无味的生活
4楼-- · 2019-01-02 20:01

Put that code in a function (the code that can't be executed on the same thread as the GUI), and to trigger that code's execution put the following.

Thread myThread= new Thread(nameOfFunction);

workerThread.Start();

Calling the start function on the thread object will cause the execution of your function call in a new thread.

查看更多
登录 后发表回答