L
Lee Alexander
Hi,
I'm trying to use AsyncOperation to execute a method in a main thread
context from a worker thread. If I run the program from a console
application then it doesn't work. If however I run it from a WindowsForms
application it does. Basically I set the name of the main thread to "Main
Thread", when the "ShouldBeInMainThreadCall" is called the
Thread.CurrentThread.Name is null. However if I run it in a WindowsForms
application it has the correct name. Could anyone help me with this?
Find below the source for the console app:
using System;
using System.Threading;
using System.ComponentModel;
namespace TestThreadAffinityEvents
{
class Program
{
private static AsyncOperation operation;
private static void DoWork()
{
operation.Post( new SendOrPostCallback( delegate( object state )
{
ShouldBeInMainThreadCall();
} ), null );
operation.OperationCompleted();
}
static void Main( string[] args )
{
Thread.CurrentThread.Name = "Main thread";
Thread workerThread = new Thread( new ThreadStart( DoWork ) );
operation = AsyncOperationManager.CreateOperation( null );
workerThread.Start();
int i = 0;
while( true )
{
Console.WriteLine( string.Format( "Hello from {0} {1}",
Thread.CurrentThread.Name, i++ ) );
Thread.Sleep( 500 );
}
}
static void ShouldBeInMainThreadCall()
{
Console.WriteLine( string.Format( "Calling you from {0}",
Thread.CurrentThread.Name ) );
}
}
}
Cheers
Lee
I'm trying to use AsyncOperation to execute a method in a main thread
context from a worker thread. If I run the program from a console
application then it doesn't work. If however I run it from a WindowsForms
application it does. Basically I set the name of the main thread to "Main
Thread", when the "ShouldBeInMainThreadCall" is called the
Thread.CurrentThread.Name is null. However if I run it in a WindowsForms
application it has the correct name. Could anyone help me with this?
Find below the source for the console app:
using System;
using System.Threading;
using System.ComponentModel;
namespace TestThreadAffinityEvents
{
class Program
{
private static AsyncOperation operation;
private static void DoWork()
{
operation.Post( new SendOrPostCallback( delegate( object state )
{
ShouldBeInMainThreadCall();
} ), null );
operation.OperationCompleted();
}
static void Main( string[] args )
{
Thread.CurrentThread.Name = "Main thread";
Thread workerThread = new Thread( new ThreadStart( DoWork ) );
operation = AsyncOperationManager.CreateOperation( null );
workerThread.Start();
int i = 0;
while( true )
{
Console.WriteLine( string.Format( "Hello from {0} {1}",
Thread.CurrentThread.Name, i++ ) );
Thread.Sleep( 500 );
}
}
static void ShouldBeInMainThreadCall()
{
Console.WriteLine( string.Format( "Calling you from {0}",
Thread.CurrentThread.Name ) );
}
}
}
Cheers
Lee