BoKKeR
BoKKeR

Reputation: 131

c# wrapping a Task into a another Task

I am trying to use inter process communication to send from one instance of my program its content to the other instance. The code I have under here is working but it makes the first instance freeze and only continues running when the second instansce is created and the data is passed back.I suspect its because messaging_server0() is not a async task. How would one approach this problem. Is there a way to make messaging_server0 async? or am I missing something?

main loop contains this piece of code

var makeTask = Task<string>.Factory.StartNew(() => pipe_server.messaging_server0());

if (makeTask.Result != null) { 
    dataGrid_logic.DataGridLoadTarget(makeTask.Result);
}

and on the other side I have messaging_server0

public static string  messaging_server0()
{
    using (var messagebus1 = new TinyMessageBus("ExampleChannel"))
    {
        string ret = null;

        messagebus1.MessageReceived += (sender, e) => ret = Encoding.UTF8.GetString(e.Message);

        while (true)
        {
            if (ret != null)
            {
                return ret;
            }
        }
    }
}

The method names are going to be refactored.

Upvotes: 0

Views: 1972

Answers (2)

BoKKeR
BoKKeR

Reputation: 131

with the help of alek kowalczyk and some digging I came up with this code

    private async void xxx()
    {
        var makeTask = Task<string>.Factory.StartNew(() => pipe_server.messaging_server());

        await pipe_server.messaging_server();
        {
            dataGrid_logic.DataGridLoadTarget(makeTask.Result);

        }
    }

plus the snippet he posted. This works perfectly. thanks

Upvotes: 0

alek kowalczyk
alek kowalczyk

Reputation: 4934

I would suggest following approach:

    public static async Task<string> messaging_server0()
    {
        using (var messagebus1 = new TinyMessageBus("ExampleChannel"))

        {
            var taskCompletition = new TaskCompletionSource<string>();

            messagebus1.MessageReceived +=
                (sender, e) =>
                {
                    var ret = Encoding.UTF8.GetString(e.Message);
                    taskCompletition.TrySetResult(ret);
                };

            return await taskCompletition.Task;
        }
    }

Obviously you would need to add some error handling, time outs if needed etc.

Upvotes: 1

Related Questions