无法从线程任务<bool>转换为系统操作

时间:2017-08-23 22:20:49

标签: c# task threadpool

我在按钮中运行任务有问题 问题是:无法从threading.task.task转换为系统操作 我在按钮

中标记了这一行

         private async void BtnStart_Click(object sender, EventArgs e)
         {

        if (String.IsNullOrEmpty( txtProxy.Text) || lstviewcomp.Items.Count==0)
        {
            MessageBox.Show("Please uploads files");
            return;
        }
        proxies = txtProxy.Text.Split('\n');
        proxycount = proxies.Length;
        foreach (string item in lstviewcomp.Items)
        {
            proxycount++;
            if (proxyCounter> proxycount)
            {
                proxyCounter = 0;
            }
            ProxyInfo = proxies[proxyCounter].Split(',');
            var result = await Task.Run( MainAsync("", "", "", "", "", "")).GetAwaiter().GetResult();// Problem in this line 


            // proxyCounter++;
        }
    }

public async Task MainAsync(string instausername,string pass,string proxyip,string proxyport,string proxyusername,string proxypass) { try { // create user session data and provide login details var userSession = new UserSessionData { UserName = instausername, Password = pass }; // create proxy handeler var httpHndler = new HttpClientHandler(); IWebProxy proxy = new WebProxy(proxyip,Convert.ToInt32(proxyport)); proxy.Credentials = new NetworkCredential(proxyusername, proxypass); httpHndler.Proxy = proxy; // create new InstaApi instance using Builder _instaApi = new InstaApiBuilder() .SetUser(userSession) .UseHttpClientHandler(httpHndler) .UseLogger(logger: new DebugFileLogger()) // use logger for requests and debug messages .SetRequestDelay(TimeSpan.FromSeconds(1)) // set delay between requests .Build();

// login txtLog.Text = txtLog.Text + $"Logging in as {userSession.UserName}"+" At "+DateTime.Now+"\n"; var logInResult = await _instaApi.LoginAsync(); if (!logInResult.Succeeded) { txtLog.Text = txtLog.Text + $"Unable to login: {logInResult.Info.Message}" + " At " + DateTime.Now + "\n"; } else { txtLog.Text = txtLog.Text + $"Logging in success : {userSession.UserName}" + " At " + DateTime.Now + "\n"; } } catch (Exception ex) { Console.WriteLine(ex); } finally { var logoutResult = Task.Run(() => _instaApi.LogoutAsync()).GetAwaiter().GetResult(); if (logoutResult.Succeeded) txtLog.Text = txtLog.Text + "Logout sucess \n"; } return false; }

2 个答案:

答案 0 :(得分:4)

public async Task MainAsync

应改为

public async Task<bool> MainAsync

然后而不是

var result = await Task.Run( MainAsync("", "", "", "", "", "")).GetAwaiter().GetResult();

你可以使用

var result = await MainAsync("", "", "", "", "", "");

此外,您还需要在以下行中使用async

var logoutResult = Task.Run(() => _instaApi.LogoutAsync()).GetAwaiter().GetResult();

=&GT;

var logoutResult = await _instaApi.LogoutAsync();

答案 1 :(得分:2)

Task.RunFunc<Task>Action(当然您可以通过另外CancellationToken)。因此,对于您的情况,您需要传递一个返回任务的函数,并且不会尝试等待void(我希望您记得您不能等待void)。只需获得任务结果:

Task.Run(() => MainAsync("", "", "", "", "", "")).GetAwaiter().GetResult();

您可以直接等待任务而不是上面的代码:

Task.Run(() => MainAsync("", "", "", "", "", "")).Wait();

但是如果你想通过任务异步地继续你的工作流程&#39;结果你的MainAsync应该返回Task<bool>,如@Olexiy Sadovnikov回答所指出并等待返回的任务。