Giter VIP home page Giter VIP logo

unused-task-warning's Introduction

unused-task-warning

When using dependency injection and async-await pattern it is possible to end up with an interface with a method that returns a Task. If this interface method is used in a synchronous method there is a likelihood that it will erroneously be run as a fire and forget method (which will not trigger inbuilt warning CS4014). In this situation this analyser generates a warning.

Can both be used as a Visual Studio extension or preferably as a project analyser available from NuGet.

Example:

using System.Threading.Tasks;

namespace AsyncAwaitProblem
{
	public interface ICallee
	{
		bool ProblemSolved { get; }
		Task SolveProblemAsync();
	}

	public class Callee : ICallee
	{
		public bool ProblemSolved { get; set; }

		public async Task SolveProblemAsync()
		{
			await Task.Delay(10);
			ProblemSolved = true;
		}
	}
	
	public class Caller
	{
		public bool DoCall()
		{
			ICallee xxx = new Callee();

			// This analyser will give a warning at the following line
			xxx.SolveProblemAsync(); // This is most likely an undesired fire and forget. 

			return xxx.ProblemSolved; // Will return false - we expected it to return true
		}
	}
}

Note that this analyser currently only checks for current known awaitable types (ex. types Task, ValueTask and ConfiguredTaskAwaitable (the type returned when using the ConfigureAwait method)). If another 'Awaitable' type is returned this analyser will not give the warning. This might be fixed in a future version.

Available from NuGet here: https://www.nuget.org/packages/Lindhart.Analyser.MissingAwaitWarning/

Available from Visual Studio marketplace here: https://marketplace.visualstudio.com/items?itemName=Lindhart.missingAwaitWarning#overview

For information on how to use analyzers check here: https://docs.microsoft.com/en-us/visualstudio/code-quality/roslyn-analyzers-overview?view=vs-2019

unused-task-warning's People

Contributors

fszewczy avatar jorisvergeer avatar maxhorstmann avatar samusaran avatar ykoksen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

unused-task-warning's Issues

Can the Nuget be installed as development asset only?

First, great work on this Nuget. Love the warnings!

It appears when the Nuget package is installed it's installed as a true dependency to the project and not a development dependency.

Here is an example of another analyzer inclusion in the project. The AsyncFixer installs itself as PrivateAssets with all which prevents its dependencies and inclusion in the output of the project.

	  <PackageReference Include="AsyncFixer" Version="1.1.6">
	    <PrivateAssets>all</PrivateAssets>
	    <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
	  </PackageReference>

The Lindhart.Analyser.MissingAwaitWarning package installs itself into the project like the below.
And because of this, it causes the System.Threading.Tasks.Extensions to be added as a dependency to the project at v4.3.0. Also it includes the library in the output.

	  <PackageReference Include="Lindhart.Analyser.MissingAwaitWarning" Version="1.2.0" />

Is it possible to update the Nuget to be development only asset? Or is this behavior by design?

ValueTask gives no warning

Hi,

I am working on some code that uses IAsyncDisposable. This returns an ValueTask (without type argument).

In the code of your analyzer has those explicitly commented out because those types do not exist in .netstandard1.3. Point is that your analyzer does not need the types at all as you only do string comparison on the full names of the types.

I created a pull request where the type list is stored as string. I use this fixed version at the moment and it works great.

#29

Many thanks for this analyzer, it is helping me greatly at the moment.

Doesn't give warning in return case

NOTE: See the added example below for more details.

I had expected the following example to give a warning, but it doesn't:

`using System.Threading.Tasks;

namespace ACF.UI.LoanOrigination.Gateway
{

public interface ICallee
{
	bool ProblemSolved { get; }
	Task<int> SolveProblemAsync();
}

public class Callee : ICallee
{
	public bool ProblemSolved { get; set; }

	public async Task<int> SolveProblemAsync()
	{
		await Task.Delay(10);
		ProblemSolved = true;
		return 1;
	}
}

public class Caller
{
	public bool DoCall()
	{
		ICallee xxx = new Callee();

		// This analyser will give a warning at the following line
		var i = xxx.SolveProblemAsync(); // This is most likely an undesired fire and forget. 

		return xxx.ProblemSolved; // Will return false - we expected it to return true
	}
}

}
`
It's not a "fire and forget", but I'd like to know that I missed the await here.

False positives for some lambda functions

Some lambda functions which does not constitute a fire and forget still causes warnings.
Examples:

        public interface ICallee { Task<int> DoSomethingAsync(); }

        public class Callee : ICallee
        {
            public async Task<int> DoSomethingAsync() => await Task.FromResult(0);
        }

        public class Caller
        {
            public async Task DoCall()
            {
                ICallee xxx = new Callee();
                
                // Functions that should not give warning but does
                DoSomething(() => xxx.DoSomethingAsync());
                Func<Func<Task>> func = () => () => xxx.DoSomethingAsync();
            }

            public void DoSomething(Func<Task> action){}

           // This should not give warning but does
            public Task TestThis(ICallee test) => test.DoSomethingAsync());
        }
        public class CallerHolder
        {
            public ICallee Callee { get; set; }
        }

In this code there are no fire and forget. Yet three warnings are given.

Analyzer doesn't detect missing awaits in lambda-like expressions

Hi!

Thanks for a very useful tool! It helped to fix a couple of very important bugs in the project I'm working at.

However, the following use cases don't seem to be covered by the analyzer:

    public static class Program
    {
        public static void Main()
        {
            Parallel.For(0, 5, i => Run2Async(i));

            void LocalFunc() => RunAsync();
            LocalFunc();

            Do();

            Console.WriteLine("Hello World!");
        }

        private static Task RunAsync()
        {
            return Task.CompletedTask;
        }

        private static Task<int> Run2Async(int i)
        {
            return Task.FromResult(i);
        }

        private static void Do() => RunAsync();
    }

I.e. expression-bodied functions and lambdas as arguments are not detected.

The analyzer works fine if the body is expanded, e.g.:

            void LocalFunc()
            {
                RunAsync();
            }

I have tested that with the NuGet versions 1.2.1 and 2.0.0-beta2. Neither the strict analyzer option did help.

Is it something that can be fixed in future versions?

Configure via editorconfig

Firstly, thanks for making this library... it really helped me clean up my code! ๐Ÿ˜ƒ

With other analyser rules I can control them in .editorconfig like this:

dotnet_diagnostic.CA1012.severity = warning

How do I do that for this analyser rule? What is its code?

False warning when using Nunits Assert.ThrowsAsync()

I created a little test project to show the issue:

using System;
using System.Threading.Tasks;
using NUnit.Framework;

namespace ConsoleApp3
{
    class TestClass
    {
        [Test]
        public async Task DoStuffTest() //Gives a warning here, even though the ImportantMethod is awaited
        {
            var service = new SomeService();
            Assert.ThrowsAsync<NotImplementedException>(async () => await service.ImportantMethod());
        }
    }

    public class SomeService
    {
        public async Task ImportantMethod()
        {
            throw new NotImplementedException();
        }
    }
}

Extension for VS2019

Hi,

Do you plan on releasing a version for VS2019? Would really appreciate it :)

No warning for missing await when using delegate

In the following example the missing await before the call of a delegate does not give a warning, even though the delegate returns an unawaited Task.

    public Task Write(Func<Stream, Task> write)
    {
        log.Add("write");
        Stream = new UnclosedStream();
        write(Stream); // <-- here, a missing await
        return Task.CompletedTask;
    }

_Originally posted by @thomaseyde in #33 (comment) - edited by @ykoksen _

Please clarify which projects are analyzed when adding to some of the projects in a solution

Hi! I'm having a hard time figuring out how to integrate it into my solution. So maybe this could just go in the readme section. This is related to a solution with multiple projects (23 in my case)
When I add the package to a project, any unused tasks in that project are warned immediately, which is great. If there is another project that references this project, unused tasks in that project are also found. However if I continue going upwards, the errors are no longer found. Example:

Domain (has nuget package)

Service (references Domain)

Web (references Service)

Errors are correctly found in Domain and in Service, but not on Web.

Could we get a clarification on how/where we should add the nuget package so that we're sure that all of our solution is analyzed?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.