Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method from a specific thread

How could I call the onCompleteCallBack method on the same thread the SomeAsyncMethod was called ?

public void SomeAsycMethod ( Action<object> onCompleteCallBack )
{
    // get the current thread 
    /* var ThisThread = Thread.CurrentThread. */

    Task.Factory.StartNew( () =>
    {
        Thread.Sleep( 1000 );// do some work;

        // lastly call the onCompleteCallBack on 'ThisThread'
        onCompleteCallBack( "some result" );

        // I am looking for something like:
        /* ThisThread.Invoke("some result"); */
    });
}
like image 602
Tono Nam Avatar asked Nov 28 '12 16:11

Tono Nam


People also ask

How do you call a method in a thread?

Java Thread run() methodThe run() method of thread class is called if the thread was constructed using a separate Runnable object otherwise this method does nothing and returns. When the run() method calls, the code specified in the run() method is executed. You can call the run() method multiple times.

How do you run a different thread in Java?

Thread creation by implementing the Runnable Interface We create a new class which implements java. lang. Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object.

When multiple threads calls the same method?

There is nothing wrong in calling same function from different threads. If you want to ensure that your variables are consistent it is advisable to provide thread synchronization mechanisms to prevent crashes, racearound conditions.

How do you call a thread in C#?

First of all create a function and create one thread in it. then after give a function name to thread for call it. Finally, call the Thread. Start method to run test() function and test() function call CheckThread() function.


2 Answers

While you can't guarantee you callback will be called on the same thread, you can guarantee it will be called in the same Synchronization Context (assuming one exists in the original call).

public void SomeAsycMethod ( Action<object> onCompleteCallBack )
{
    // get the current context
    var context = SynchronizationContext.Current;

    Task.Factory.StartNew( () =>
    {
        Thread.Sleep( 1000 );// do some work;

        // lastly call the onCompleteCallBack on 'ThisThread'
        onCompleteCallBack( "some result" );

        // I am looking for something like:
        context.Post(s => onCompleteCallBack ("some result"), null); 
    });
}

For example, in a Windows Forms or WPF program, the above will make sure that the callback is called on the GUI thread (via the message loop or dispatcher, accordingly). Similarly for ASP.NET context.

Having said that, I agree with Justin Harvey in that returning a Task<T> will probably be a better design.

like image 153
Ohad Schneider Avatar answered Sep 21 '22 20:09

Ohad Schneider


Actually if you're using Task-based asynchronous programming I suggested you refactor your code to return Task<T> and give an ability to your client itself to decide in what context to call callback method (and facilitate future migration to C# 5.0 ;):

public Task<string> SomeMethodAsync()
{
   return Task.Factory.StartNew(() => "some result");
}

If you definitely know that you're going to call this method from UI thread you can use following:

var task = SomeMethodAsync();
task.ContinueWith(t => textBox.Text = t.Result, TaskScheduler.FromSynchronizationContext);

This approach is better because it provide more clear separation of concern and give an ability to use your asynchronous method in any context without any dependencies to synchronization context. Some client can call this method from UI thread (and in this case TaskScheduler.FromSynchronizationContext would behave as expected - your "continuation" would be called in UI thread), some of them could use your method from non-UI thread as well without such requirements like processing results in the same thread that initiate asynchronous operation.

Task<T> is a perfect class that represents asynchronous operation as a first class object that helps not only obtain only more declarative code but more clear, easy to read and easy to test (you can easily mock this method and return "fake" task object).

like image 39
Sergey Teplyakov Avatar answered Sep 24 '22 20:09

Sergey Teplyakov