planetarium / libplanet

Blockchain in C#/.NET for on-chain, decentralized gaming
https://docs.libplanet.io/
GNU Lesser General Public License v2.1
506 stars 142 forks source link

Asynchronous Blockchain.MineBlock() #29

Closed dahlia closed 4 years ago

dahlia commented 5 years ago

In Unity Engine the current block mining API blocks (serializes the flow) so that the event loop cannot switch the context to other cooperative tasks. We should prevent it by providing an async interface of Blockchain.MineBlock().

longfin commented 5 years ago

At first I thought to add the interface like below.

Task<Block<T>> Blockchain.MineBlockAsync(Address rewardBenficiary);
IEnumerator Blockchain.MineBlock(Address rewardBeneficiary, out Block<T> block); 
// or
IEnumerator Blockchain.MineBlock(Address rewardBeneficiary, Action<Block<T>> onMined); 

But there is some points to think about... (If I know something wrong, please comment.)

We can still add an async / await style API, but it does not come up with any good utility right now. Instead I suggest workaround for Unity like below

        public IEnumerator Mine(Address address)
        {
            while (true)
            {
                var task = Task.Run(() => blocks.MineBlock(address));
                yield return new WaitUntil(() => task.IsCompleted);
                Debug.Log($"mined {task.Result.Index}");
            }
        }

        private void Awake()
        {
             StartCoroutine(Mine(UserAddress));
        }

cc

@ipdae @kijun

limebell commented 4 years ago

I guess #517 closes this issue.