简体   繁体   中英

Return of async method

I have async method:

public  async Task CreateAndWriteAsyncToFile()
        {
            using (FileStream stream = new FileStream("test.dat", FileMode.Create,FileAccess.Write, FileShare.None, 4096, true))
            {
                byte[] data = new byte[100000];
                new Random().NextBytes(data);

                await  stream.WriteAsync(data, 0, data.Length);
            }
        }

Compiler complains :

The return type of async method must be void, Task or Task not all code paths returns value.

How to solve this method

There's nothing wrong with your code, the issue seems that you have another Task type defined somewhere in your project. change the method signature to:

public async System.Threading.Tasks.Task CreateAndWriteAsyncToFile(){ ... }

Just to be sure, check if you did import the System.Threading.Tasks namespace. If you accidentally created a Task class (Visual Studio will suggest you to create a class if it doesn't exists) be sure to remove it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM