最简单的在C#中做一个发射后不管方式方法是什么?最简单、中做、方式、方法

2023-09-02 01:22:59 作者:最后的最后我们还是分开了

我在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());
 
怎么把知网的外文文献翻译成中文 PDF格式的英文文献怎么翻译成中文 教你一招最简单快速的办法...

正如刚才 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.