什么是用于包装同步code到异步方法的最佳途径 [英] What is the best way for wrapping synchronous code into asynchronous method

查看:81
本文介绍了什么是用于包装同步code到异步方法的最佳途径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建使用异步await方法的应用程序。但对我来说是一个大问题,使用它们。阅读几篇文章后,我仍然不知道什么是我的包重同步操作异步方法的最佳途径。

I am creating an application with using async-await methods. But There is a large problem for me with using them. After reading few articles I still don't know what is the best way for wrapping my heavy sync operations to async methods.

我有两个想法。哪一个是最好的?

I have 2 ideas. Which one is the best?

1)当前的实现。

    private Task<List<UploadedTestModel>> ParseTestFiles(List<string> filesContent)
    {
        var tcs = new TaskCompletionSource<List<UploadedTestModel>>();
        Task.Run(() =>
        {
            var resultList = new List<UploadedTestModel>();
            foreach (var testBody in filesContent)
            {
                try
                {
                    var currentCulture = Thread.CurrentThread.CurrentCulture;
                    var serializerSettings = new JsonSerializerSettings
                    {
                        Culture = currentCulture
                    };

                    var parsedData = JsonConvert.DeserializeObject<UploadedTestModel>(testBody, serializerSettings);
                    resultList.Add(parsedData);
                }
                catch(Exception exception)
                {
                    tcs.SetException(exception);
                }
            }
            tcs.SetResult(resultList);
        });
        return tcs.Task;
    }

我使用Task.Run和TaskCompletionSource

I'm using Task.Run and TaskCompletionSource

2)仅使用Task.Run没有TaskCompletionSource

2) Using only Task.Run without TaskCompletionSource

    private Task<List<UploadedTestModel>> ParseTestFiles(List<string> filesContent)
    {
        return Task.Run(() =>
        {
           . . . .
           return resultList;          
        });
    }

感谢您为您的关注。

推荐答案

我会用也没有。你会说谎谁调用你的方法调用。当你暴露一个异步操作,调用者希望它是自然地同步的,这是有它背后做的工作没有线程。

I would use neither. You'll be lying to whoever invokes your method call. When you expose an async operation, the callers expect it to be naturally asynchronous, meaning there is no thread behind it doing work.

您所有的方法都是inherintly同步的,你应该将它们公开为如此。把它留给调用者,如果他想同步调用,或用线程和队列在那里,不决定由他们决定。

All your methods are inherintly synchronous, and you should expose them as so. Leave it up to the caller to decide if he wants to invoke them synchronously or use a thread and queue it there, don't decide for them.

有一个名为伟大的文章我应该揭露异步包装同步方法<? / A>史蒂芬Toub其中谈到了所有的理由不这样做你想要做的事。我建议阅读。

There is great article called Should I expose asynchronous wrappers for synchronous methods? by Stephan Toub which talks about all the reasons not to do what you're trying to do. I suggest reading it.

这篇关于什么是用于包装同步code到异步方法的最佳途径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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