c# – 从特定线程调用方法

c# – 从特定线程调用方法,第1张

概述我如何在调用SomeAsyncMethod的同一线程上调用onCompleteCallBack方法? public void SomeAsycMethod ( Action<object> onCompleteCallBack ){ // get the current thread /* var ThisThread = Thread.CurrentThread. */ 我如何在调用SomeAsyncmethod的同一线程上调用onCompleteCallBack方法?
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"); */    });}
解决方法 虽然你不能保证你会在同一个线程上调用回调,但你可以保证它将在同一个 Synchronization Context中被调用(假设原始调用中存在一个).
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);     });}

例如,在windows窗体或WPF程序中,上面将确保在GUI线程上调用回调(相应地通过消息循环或调度程序).类似于ASP.NET上下文.

话虽如此,我同意Justin Harvey的回复任务< T>可能会是一个更好的设计.

总结

以上是内存溢出为你收集整理的c# – 从特定线程调用方法全部内容,希望文章能够帮你解决c# – 从特定线程调用方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/1248344.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-07
下一篇2022-06-07

发表评论

登录后才能评论

评论列表(0条)

    保存