最简单的在C#中做一个发射后不管方式方法是什么? [英] Simplest way to do a fire and forget method in C#?

查看:168
本文介绍了最简单的在C#中做一个发射后不管方式方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在WCF中看到他们有[OperationContract的(IsOneWay =真)]属性。但是,WCF似乎是一种缓慢而沉重的只是做创建非阻塞功能。理想情况下,会像静态无效非阻塞MethodFoo(){},但我不认为存在。

什么是创建一个非阻塞方法调用在C#中的最快方法是什么?

例如。

 类Foo
{
    静态无效的主要()
    {
        FireAway(); //没有回调,走开
        Console.WriteLine(立即发生);
    }

    静态无效FireAway()
    {
        System.Threading.Thread.Sleep(5000);
        Console.WriteLine(10秒以后);
    }
}
 

NB :每个人都读这应该想想,如果他们真正想要的方式来完成。 (见#2顶部回答)如果该方法已经完成,那么在一些地方,像一个ASP.NET应用程序,你需要做些什么来阻止,并保持线程活着。否则,这可能导致火忘了,但是,从未真正-执行,在这种情况下,当然,它会更简单写没有code在所有。 ( A的是如何工作的ASP.NET 很好的说明)

解决方案

ThreadPool.QueueUserWorkItem(O => FireAway() );

(五年后......)

  Task.Run(()=> FireAway());
 

正如刚才 luisperezphd

I saw in WCF they have the [OperationContract(IsOneWay = true)] attribute. But WCF seems kind of slow and heavy just to do create a nonblocking function. Ideally there would be something like static void nonblocking MethodFoo(){}, but I don't think that exists.

What is the quickest way to create a nonblocking method call in c#?

E.g.

class Foo
{
    static void Main()
    {
        FireAway(); //No callback, just go away
        Console.WriteLine("Happens immediately");
    }

    static void FireAway()
    {
        System.Threading.Thread.Sleep(5000);
        Console.WriteLine("5 seconds later");
    }
}

NB: Everyone reading this should think about if they actually want the method to finish. (See #2 top answer) If the method has to finish, then in some places, like an ASP.NET application, you will need to do something to block and keep the thread alive. Otherwise, this could lead to "fire-forget-but-never-actually-execute", in which case,of course, it would be simpler to write no code at all. (A good description of how this works in ASP.NET)

解决方案

ThreadPool.QueueUserWorkItem(o => FireAway());

(five years later...)

Task.Run(() => FireAway());

as pointed out by luisperezphd.

这篇关于最简单的在C#中做一个发射后不管方式方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆