Task.Factory And Process.Parallel - task-parallel-library

Question : Some class is having M method and M method is calling M1 and M2 method logic through Task.Factory.
M Method Logic Code:
Task.Factory.StartNew(() => ProcessAndSendResultAsync(ConfigKey, content));
Task.Factory.StartNew(() => ProcessProcessorsInParalle(ConfigKey, content));
M1 Method Logic:
M1 method has been invoked through taskfactory from M method and M1 method is having some prorocessing logic.
M2 Method Logic:
M2 method has been invoked through taskfactory from M method and Somewhere Created Mulitple processors(in C# logic) and that processors getting invoked in parllel using parallel.foreach in m2 method.
Parallel.ForEach(processes, (p) =>
{
p.Process(content, configkey);
});
How this logic can improved or does it have any performance impact?

The thread pool thread executing ProcessProcessorsInParalle is blocked while performing the Parallel.ForEach, essentially wasting that thread. A small optimization would be to run each call to Process in a TPL task.
var processTasks = processes.Select(
p => Task.Factory.StartNew(() => p.Process(content, configkey))).ToList();
If you need to perform further processing after the Process calls have finished, you can move the rest of ProcessProcessorsInParalle into a separate method and invoke it as continuation.
Task.Factory.ContinueWhenAll(processTasks, t => FinishProcessInParallel());
That said, in general, you need to profile your application to know if it has performance problems.

Related

Why does the querySkuDetails need to run in IO context?

According to https://developer.android.com/google/play/billing/integrate the billingClient.querySkuDetails is called with withContext(Dispatchers.IO)
fun querySkuDetails() {
val skuList = ArrayList<String>()
skuList.add("premium_upgrade")
skuList.add("gas")
val params = SkuDetailsParams.newBuilder()
params.setSkusList(skuList).setType(SkuType.INAPP)
val skuDetailsResult = withContext(Dispatchers.IO) {
billingClient.querySkuDetails(params.build())
}
// Process the result.
}
I am curious which benefits it gives as querySkuDetails is already a suspending function. So what do i gain here.
I could write the same code with
val skuDetailsResult = coroutineScope {
billingClient.querySkuDetails(params.build())
}
There is no more context and i don't know how to download the source code of the billing client.
The underlying method being called is querySkuDetailsAsync which takes a callback and performs the network request asynchronously.
You are correct that withContext(Dispatchers.IO) is not needed there, it actually introduces unnecessary overhead.
Gotten from https://stackoverflow.com/a/62182736/6167844
It seems to be a common misconception, that just because IO is being performed by a suspend function, you must call it in Dispatchers.IO, which is unnecessary (and can be expensive).
suspending functions by convention don't block the calling thread and internally blocks in Dispatchers.IO if need be.

Does CreateFromObservable works asynchrony?

I'm trying use ReactiveUI 7.4 in WPF project, and I think it's great framework. But it causes great difficulties in studying the absence, or the outdated documentation.
In doc https://docs.reactiveui.net/en/user-guide/commands/asynchronous-synchronous.html says so CreateFromObservable is asynchrony, but in my example it's run syncronly.
RefreshList = ReactiveCommand.CreateFromObservable<ReactiveList<ClientDto>>(
() => Observable
.Return(_clientsService.GetClientsList())
and latter
_isBusy = this.WhenAnyObservable(x => x.RefreshList.IsExecuting)
.ToProperty(this, vm => vm.IsBusy);
when i do InvokeCommand method runs syncronly, and IsExecuting observe only after GetClientsList() completed (change to false and after to true). But variand with task works:
RefreshList = ReactiveCommand.CreateFromTask(async _ =>
{
return await Task.Run(() => _clientsService.GetClientsList());
}
);
Is it bug? Or changes in framework?
PS I also trying plays with SubscribeOn and ObservableOn but nothing helps (((.
Observable.Return() does it's work on the current thread, which means it's blocking. In your case the current thread is the UI thread.
You can specify a scheduler, but that only affects where the value is returned, not where it's produced.
I've written about Observable.Return() and how it behaves in this blog post.
It looks like _clientsService.GetClientsList() is implemented synchronously. To make it asynchronous you can move the work to the task pool. You've already done this by running it in a Task. It's also possible to use `Observable.Start()´:
RefreshList = ReactiveCommand.CreateFromObservable<ReactiveList<ClientDto>>(
() => Observable
.Start(_clientsService.GetClientsList(), RxApp.TaskpoolScheduler);

How do I set up a verifiable expectation on a mocked async method? [duplicate]

This question already has answers here:
How can I tell Moq to return a Task?
(5 answers)
Closed 6 years ago.
I'm trying to use Moq to test integration between a WebAPI controller and a Redis database, using the StackExchange.Redis client, and cannot work out how to set up a verifiable expectation on a mocked async method that includes a callback or some other assertion behaviour.
Ordinarily, I'd use the following syntax:
const string KEY = "some_key";
var db = new Mock<IDatabase>();
db.Setup(d => d.HashSetAsync(KEY, It.IsAny<HashEntry[]>(),It.IsAny<CommandFlags>()))
.Callback<RedisKey,HashEntry[],CommandFlags>((key, hash, flags) => {
hash.ShouldContain(entry => entry.Name == "customerid");
hash.ShouldContain(entry => entry.Name == "quotenumber");
})
.Verifiable();
But this is giving me:
'Moq.Language.Flow.IReturnsThrows<StackExchange.Redis.IDatabase,System.Threading.Tasks.Task>' does not contain a definition for 'Verifiable' and no extension method 'Verifiable' accepting a first argument of type 'Moq.Language.Flow.IReturnsThrows' could be found (are you missing a using directive or an assembly reference?)
If I change db.HashSetAsync to db.HashSet in the Setup invocation, it works as expected. It appears that the setting a Callback on a regular method returns an ICallbackResult but setting a callback on an async method invocation returns an IReturnsThrows - and I'm not sure how you mark one of those as verifiable. Any ideas?
For async methods you need to return a completed Task from the setup before using a callback
have a look here:
Using Moq to mock an asynchronous method for a unit test
You're creating a task but never starting it, so it's never
completing. However, don't just start the task - instead, change to
using Task.FromResult<TResult> which will give you a task which has
already completed:
this works
const string KEY = "some_key";
var db = new Mock<IDatabase>();
db.Setup(d => d.HashSetAsync(KEY, It.IsAny<HashEntry[]>(), It.IsAny<CommandFlags>()))
.Returns(Task.FromResult<object>(null))
.Callback<RedisKey, HashEntry[], CommandFlags>((key, hash, flags) => {
hash.ShouldContain(entry => entry.Name == "customerid");
hash.ShouldContain(entry => entry.Name == "quotenumber");
})
.Verifiable();

Does Dart create new methods for each new instance?

I'm currently designing a class structure for a project I'm working on. I have a method that uses one instance state. I don't now wheter it's better to make this method static and parse this instance state as an argument or just tie the method to the instance.
If performance was no issue I would tie the method without any doubt to the instance, because it's much cleaner that way. But in my case performance will be really crucial. So, does it make any difference performance-wise to make the method static / non-static?
If it makes no difference, will that be true for the generated *.dart.js javascript aswell?
Edit:
After reading my own question it's not really coherent. I will try to formulate it again, but clearer.
This code ...
class MyClass {
void foo() {}
}
void main() {
MyClass a = new MyClass();
MyClass b = new MyClass();
print(a.foo == b.foo);
}
... outputs false. This make me think that for each new instance a new method is created. If that is true this seems to me as a waste of memory. So, does each new instance create a copy of all it's bound methods?
PS: The question is basically the same as this question, but then for Dart.
No, creating two instances doesn't duplicate the methods. Methods are like static functions where the object instance is passesd as argument with the name this.
Don't worry too much about performance before you run into actual performance issues especially at such micro-level.
Usually performance isn't a matter for the bigger part of your applications code base because most of the code is usually run very seldom.
When you run into performance issues you can investigate and find the real hot spots that are executed often enough so that optimization actually makes a difference.
Dart classes don't have different methods for different instances.
There is only one method per class.
Extracting a function creates a new function object every time you do it, and those objects may or may not be equal depending on which function you extract from which objects:
class MyClass {
void foo() {}
}
void main() {
MyClass a = new MyClass();
MyClass b = new MyClass();
print(a.foo == b.foo); // False.
print(a.foo == a.foo); // True
print(identical(a.foo, a.foo)); // False!
}
When you perform a method extraction from an object, you create a new object. The new object is a "closure" which contains the function to call and the object to call it on. Two such closures are equal (according to operator==) if they refer to the same function on the same object. That's why a.foo and b.foo are not equal - they are equivalent to () => a.foo() and () => b.foo() respectively, and since a and b are not the same object, the function objects are not considered equal.

creating an instance of another object in javascript

I want to know whether this sentence is correct?
You can do:
var a = new A();
if and only if A is instanceof Function.
Simply you can create an instance of function and you know a function is an object. Why can't we create an instance of other user-defined objects? Like this:
var b={};
var c = new b(); //error
EDIT: How can I change b so that I can create an instance of that?
You can actually use Object.create() to have some sugar around ECMAscript's prototypal nature. Like
var b = { };
var c = Object.create( b );
Now, c will have b on its prototype chain. ECMAscript or more precisely, prototypal inheritance doesn't work exactly the same way as a "classical inheritance". By calling new when invoking a function, you actually receiving a newly created object aswell. You can modify and access that object via the this value within that such called constructor function.
However, you didn't inherit anything so far. You would need to create and fill the .prototype - object for your constructor function before you create instances of it. This pattern annoyed lots of people, so ES5 brought as a more convinient way to directly inherit from other objects using Object.create().
Simply you can create an instance of function and you know a function is an object. Why can't we create an instance of other user-defined objects?
It’s not quite correct to say “you can create an instance of function”. The new keyword is a bit misleading - it makes JavaScript look like it implements object-orientation using classes, when in fact it doesn’t.
What you’re actually doing with new A() is creating an object using the constructor function A. The new keyword tells the JavaScript interpreter to return an object from A - specifically the object referred to as this inside of A.
EDIT: How can I change b so that I can create an instance of that?
In your example, b is an object (var b={};). If you change b into a constructor function, then you can create objects using it. (By convention, constructor functions in JavaScript start with capital letters.)
So:
function B () {
}
var c = new B();
You can add things to the prototype object of B, and they’ll be accessible on c too (and on any other objects you create using B):
function B () {
}
B.prototype.NAME = 'B';
B.prototype.hello = function () {
alert('Hello!');
}
var c = new B();
c.NAME // 'B'
c.hello() // alerts 'Hello!'
Short answer: The new operator requires its operand to have a special internal method [[Construct]] that generic objects do not have.
Long answer:
11.2.2 The new Operator
The production NewExpression : new NewExpression is evaluated as follows:
1. Evaluate NewExpression.
2. Call GetValue(Result(1)).
3. If Type(Result(2)) is not Object, throw a TypeError exception.
4. If Result(2) does not implement the internal [[Construct]] method, throw a TypeError exception.
5. Call the [[Construct]] method on Result(2), providing no arguments (that is, an empty list of arguments).
6. Return Result(5).
The production MemberExpression : new MemberExpression Arguments is evaluated as follows:
1. Evaluate MemberExpression.
2. Call GetValue(Result(1)).
3. Evaluate Arguments, producing an internal list of argument values (11.2.4).
4. If Type(Result(2)) is not Object, throw a TypeError exception.
5. If Result(2) does not implement the internal [[Construct]] method, throw a TypeError exception.
6. Call the [[Construct]] method on Result(2), providing the list Result(3) as the argument values.
7. Return Result(6).
You can also do
var b = new a.constructor();

Resources