static int TestThread( int data, int ms)
{
Console .WriteLine( "TestThread started" );
Thread.Sleep(ms);
Console .WriteLine( "TestThread completed" );
return ++data;
}
public delegate int TestThreadDelegate( int data, int ms);
* This source code was highlighted with Source Code Highlighter .
static void Main()
{
TestThreadDelegate d1 = TestThread;
d1.BeginInvoke(1, 3000, TestThreadCompleted, d1);
for ( int i = 0; i < 100; i++)
{
Console .Write( "." );
Thread.Sleep(50);
}
}
static void TestThreadCompleted(IAsyncResult ar)
{
if (ar == null ) throw new ArgumentNullException( "ar" );
TestThreadDelegate d1 = ar.AsyncState as TestThreadDelegate;
Trace.Assert(d1 != null , "Invalid object type" );
int result = d1.EndInvoke(ar);
Console .WriteLine( "result: {0}" , result);
}
* This source code was highlighted with Source Code Highlighter .
using System;
using System.Threading;
namespace Csharp.Threading.FirstThread
{
class Program
{
static void Main( string [] args)
{
Thread t1 = new Thread(ThreadMain);
t1.Start();
Console .WriteLine( "This is the main thread." );
}
static void ThreadMain()
{
Console .WriteLine( "In thread." );
}
}
}
* This source code was highlighted with Source Code Highlighter .
public class MyThread
{
private string data;
public MyThread( string data)
{
this .data = data;
}
public void ThreadMain()
{
Console .WriteLine( "Running in a thread, data: {0}" , data);
}
}
* This source code was highlighted with Source Code Highlighter .
MyThread obj = new myThread(“text”);
Thread tr = new Thread(obj.ThreadMain);
tr.Start();
* This source code was highlighted with Source Code Highlighter .
using System;
using System.Threading;
namespace Csharp.Threading.Pools
{
class Program
{
static void Main()
{
for ( int i = 0; i < 5; i++)
{
ThreadPool.QueueUserWorkItem(JobForAThread);
}
Thread.Sleep(5000);
}
static void JobForAThread( object state)
{
for ( int i = 0; i < 3; i++)
{
Console .WriteLine( "loop {0}, running inside pooled thread {1}" , i,
Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(10);
}
}
}
}
* This source code was highlighted with Source Code Highlighter .
Source: https://habr.com/ru/post/67693/
All Articles