通过线程返回值

时间:2017-02-13 15:22:25

标签: c# .net multithreading return

有这个:

public Item_DataColl invoke_command_READ(string UCPTName)
{
    networkingThread = new Thread(new ParameterizedThreadStart(thread_command_READ));
    networkingThread.Start(new readingThreadParameter(UCPTName));
}
private Item_DataColl thread_command_READ_result(object parameter)
{
    readingThreadParameter p = parameter as readingThreadParameter;
    Item item;

    if (p.UCPT_Name != null)
    {
        Item_DataColl resultSet;
        try
        {
            OnProgressBarUpdate(progressBar.UnknownEnd);
            resultSet = connector.command_READ(p.UCPT_Name);
            readOperationDone(resultSet);
            OnConsoleWriting(string.Format("[READING] Lecture réussie : {0} = {1}", ((Dp_Data)resultSet.Item[0]).UCPTname, ((Dp_Data)resultSet.Item[0]).UCPTvalue[0].Value), ILonConnectorConsoleResultType.RESULT);
            return resultSet; // HERE, I WANT TO RETURN RESULT
        }
        catch (Exception e)
        {
            OnConsoleWriting(e.ToString(), ILonConnectorConsoleResultType.ERROR);
        }
        finally
        {
            OnProgressBarUpdate(progressBar.Invisible);
        }
    }
}

我试图执行SOAP请求并发送结果。为了使应用程序"非阻塞",我使用了线程。

soap请求工作正常,但我很难在线程结束后发送结果。我必须跟踪它并在线程结束时将结果发送回另一个类。

我该怎么做?

1 个答案:

答案 0 :(得分:-1)

嗯..这个解决方案可以写得更好......但我目前正在使用您已发布的代码。

方法 - 使用回调(带代理):

首先 - 在类范围中声明一个委托

private Action<Item_DataColl> OnResultSetComplete;

第二 - 在调用线程之前为委托分配一些函数

public Item_DataColl invoke_command_READ(string UCPTName)
    {
        OnResultSetComplete = (resukts) =>
        {
             // DO SOMETHING HERE
        };
        networkingThread = new Thread(new ParameterizedThreadStart(thread_command_READ));
        networkingThread.Start(new readingThreadParameter(UCPTName));
    }

最后 - 更改您的阅读结果功能:

private Item_DataColl thread_command_READ_result(object parameter)
    {
        readingThreadParameter p = parameter as readingThreadParameter;
        Item item;

        if (p.UCPT_Name != null)
        {
            Item_DataColl resultSet;
            try
            {
                OnProgressBarUpdate(progressBar.UnknownEnd);
                resultSet = connector.command_READ(p.UCPT_Name);
                readOperationDone(resultSet);
                OnConsoleWriting(string.Format("[READING] Lecture réussie : {0} = {1}", ((Dp_Data)resultSet.Item[0]).UCPTname, ((Dp_Data)resultSet.Item[0]).UCPTvalue[0].Value), ILonConnectorConsoleResultType.RESULT);
                if (OnResultSetComplete != null) OnResultSetComplete(resultSet); 
            }
            catch (Exception e)
            {
                OnConsoleWriting(e.ToString(), ILonConnectorConsoleResultType.ERROR);
            }
            finally
            {
                OnProgressBarUpdate(progressBar.Invisible);
            }
        }
    }