C# How to start an async method without await its complete?

前端 未结 6 1439
醉酒成梦
醉酒成梦 2021-02-05 08:12

Sometimes I need to start an async job which works very slow. I don\'t care if that job success and I need to continue working on my current thread.

Like sometimes I nee

相关标签:
6条回答
  • 2021-02-05 08:22

    I am curious why this hasn't been suggested.

    new Thread(() =>
    {
        Thread.CurrentThread.IsBackground = true;
        //what ever code here...e.g.
        DoSomething();
        UpdateSomething();
    }).Start();  
    

    It just fires off a separate thread.

    0 讨论(0)
  • 2021-02-05 08:28

    It all depends on what your Async method accepts. Normally it will accept a "special" class that also holds an event. You can subscribe your callback method to that event and pass it along with the method. When it's finished, your callback method will be called.

    An example of this (for sockets) would be:

        public void CreateSocket()
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SocketAsyncEventArgs sockAsync = new SocketAsyncEventArgs();
            sockAsync.Completed += SockAsync_Completed;
    
            s.ConnectAsync(sockAsync);
        }
    
        private void SockAsync_Completed(object sender, SocketAsyncEventArgs e)
        {
            //Do stuff with your callback object.
        }
    

    It all depends on what the method you are trying to call can accept. I would look at the documentation for more help on that specifically.

    0 讨论(0)
  • 2021-02-05 08:40

    If you need to use async in your function you can also use a discard variable and don't use await. This is also usefull if you have multiple async function calls but you don't need to wait for all of them.

    public async function(){
        var tmp = await asyncfunction();
        ...
        _ = _httpClient.PutAsync(url, content);
        ...
    }
    
    0 讨论(0)
  • 2021-02-05 08:42

    A standalone discard is the best way to avoid this warning.

    _ = Task.Run(() =>  _emailService.SendEmailAsync());
    

    Discards are dummy variables and can be used to ignore the Task object returned by an asynchronous operation.

    https://docs.microsoft.com/en-us/dotnet/csharp/discards#a-standalone-discard

    0 讨论(0)
  • 2021-02-05 08:43

    As Amadan told in the comment that, you need to remove async from your function. then it will stop giving you the warning.

    // This method has to be async
    public Response SomeHTTPAction()
    {
         // Some logic...
         // ...
         // Send an Email but don't care if it successfully sent.
         Task.Factory.StartNew(() =>  _emailService.SendEmailAsync());
         return MyRespond();
    }
    

    and Task.Factory.StartNew(() => _emailService.SendEmailAsync()); will indeed work on a new thread.

    0 讨论(0)
  • 2021-02-05 08:44

    If you truly just want to fire and forget. Simply don't call use await.

    // It is a good idea to add CancellationTokens
    var asyncProcedure = SomeHTTPAction(cancellationToken).ConfigureAwait(false);
    
    // Or If not simply do:
    var asyncProcedure = SomeHTTPAction().ConfigureAwait(false);
    

    If you want to use the result output later its gets trickier. But if it is truly fire and forget the above should work

    A Cancellation token allows interrupts and canceling procedures. If you are using Cancellation token you will need to use it everywhere from the retrieval straight through to the calling method (Turtles all the way down).

    I used ConfigureAwait(false) to prevent deadlocks. Here for more information

    0 讨论(0)
提交回复
热议问题