G
G
Georgy Kuznetsov2021-06-20 09:43:36
C++ / C#
Georgy Kuznetsov, 2021-06-20 09:43:36

How is Task.Run used when the target method has parameters?

Let's say there is a code like this

private void window_KeyDown(object sender, KeyEventArgs e)
{
        ...???...
}

private async Task moveObj(KeyEventArgs e)
{
        await obj.handleKeyArrow(e);
}


Here are two questions: is it appropriate for us to use task.run and if so, how to pass a method with parameters there

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ilya, 2021-06-20
@JoeSmith3100

If it's WPF then

private async void window_KeyDown(object sender, KeyEventArgs e)
{
    await moveObj(e);
}

F
freeExec, 2021-06-20
@freeExec

There is also an overload when the task can be sent an object as a parameter.

N
none7, 2021-06-20
@none7

static Task ProxyRun<T1,T2> (Action<T1> action, T1 arg1,) {
    return Task.Run(() => action(arg1));
}
static Task ProxyRun<T1,T2> (Action<T1,T2> action, T1 arg1, T2 arg2) {
    return Task.Run(() => action(arg1, arg2));
}
static Task<TResult> ProxyRun<T1,TResult> (Func<T1,T2,TResult> action, T1 arg1,) {
    return Task<TResult>.Run(() => action(arg1, arg2));
}
static Task<TResult> ProxyRun<T1,T2,TResult> (Func<T1,T2,TResult> action, T1 arg1, T2 arg2) {
    return Task<TResult>.Run(() => action(arg1, arg2));
}
static Task StartNew<T1,T2> (this TaskFactory taskFactory, Action<T1,T2> action, T1 arg1, T2 arg2) {
     return taskFactory.StartNew(() => action(arg1, arg2));
}

And you can spawn such wrappers as much as you like, even if the existing varieties of Func and Action are not enough, you can always add them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question